Go Back   vb.org Archive > vBulletin Article Depository > Read An Article > vBulletin 4 Articles
FAQ Community Calendar Today's Posts Search

Reply
 
Thread Tools
[HOW TO - vB4] Rendering templates and registering variables - a short guide
cellarius's Avatar
cellarius
Join Date: Aug 2005
Posts: 1,987

 

Show Printable Version Email this Page Subscription
cellarius cellarius is offline 11-15-2009, 10:00 PM

Introduction

Starting with vB4, templates no longer get output using eval:
PHP Code:
eval('$mytemplate = "' fetch_template('mytemplate') . '";'); 
is outdated.
What's more: Variables and arrays from plugins that are executed on a page no longer can automatically be accessed in the templates of that page. They need to be registered first.
.
Basic functionality to render templates and register all variables/arrays you want to use inside

PHP Code:
/* Some Code, setting variables, (multidimensional) array */
$my_var "abc";
$my_array = array(
        
'key1' => 'value1',
        
'key2' => array(
                '
key21' => 'value21',
                '
key22' => 'value22'
        '
)
    );

/* render template and register variables */
$templater vB_Template::create('mytemplate');
    
$templater->register('my_var'$my_var);
    
$templater->register('my_array'$my_array);
$templater->render(); 
  • The first line provides the template that is to be rendered, using the new vB_Template class (vB_Template::create). The method gets passed the name of the template as an argument.
  • The following two lines register a variable and an array that we want to use in our template. Arguments passed are 1. the name you want to use to access the variable, and 2. the variable from the code you want to register. You can register as many variables/arrays as you want. Just remember you have to register every variable and array that you want to use in your custom template in this way. If you don't register them, they will not be available.
  • The fourth line renders the template ($templater->render()).
In the template you know will be able to use the registered variables/arrays in this way:
HTML Code:
{vb:raw my_var}
{vb:raw my_array.key1}
{vb:raw my_array.key2.key21}
Note the last one: multidimensional arrays are perfectly possible.
.
.
.
Now, with the result of the rendering we can do several things:
.
Output template directly - custom pages


PHP Code:
$templater vB_Template::create('mytemplate');
    
$templater->register_page_templates(); 
    
$templater->register('my_var'$my_var);
    
$templater->register('my_array'$my_array);
print_output($templater->render()); 
This immediatly outputs the template. Use this if you have created your own page, for example.
Note the second line, which is special for this type of use:
PHP Code:
$templater->register_page_templates(); 
This auto-registers the page level templates header, footer and headinclude that you will use in the template of your custom page.
.
Use a template hook


PHP Code:
$templater vB_Template::create('mytemplate');
    
$templater->register('my_var'$my_var);
    
$templater->register('my_array'$my_array);
$template_hook[forumhome_wgo_pos2] .= $templater->render(); 
The template will be shown using the choosen template hook (for example: $template_hook[forumhome_wgo_pos2]). See the dot before the = in the last line? The hook may be used by other modifications, too, so we don't want to overwrite it, but rather append our code to it, conserving everything that might already be there.
.
Save into a variable for later use in custom template
PHP Code:
$templater vB_Template::create('mytemplate');
    
$templater->register('my_var'$my_var);
    
$templater->register('my_array'$my_array);
$mytemplate_rendered $templater->render(); 
Now we have saved the rendered template into a variable. This variable in turn we can later on register in another template, if we want:
PHP Code:
$templater vB_Template::create('my_other_template');
     
$templater->register('my_template_rendered'$my_template_rendered);
 
print_output($templater->render()); 
Again, inside my_other_template we now could call
HTML Code:
{vb:raw my_template_rendered}
If you're running the first template call inside a loop, you may want to use .= instead of = in the last line, so that the results of every loop get added instead of overwriting the existing. But that depends, of course.
.
Save into an array and preregister to use in an existing/stock template

PHP Code:
$templater vB_Template::create('mytemplate');
    
$templater->register('my_var'$my_var);
    
$templater->register('my_array'$my_array);
$templatevalues['my_insertvar'] = $templater->render();
vB_Template::preRegister('FORUMHOME'$templatevalues); 
  • This is another, more flexible method to save the rendered template into a variable for future use in an already existing template. In this example, we want to show our own rendered template on forumhome.
  • Problem is: We have no direct way to register variables for already existing templates like FORUMHOME. It's created and rendered in the files, and we don't want to mess there.
  • To help with this, a new method was created for vB_Template class, called preRegister. Using this, we can pass our data to FORUMHOME before it is rendered. Note that the data needs to be saved into an array ($templatevalues['my_insertvar']), a simple variable will throw an error. In the last line the array is preregistered; you need to pass as arguments 1. the name of the existing template and 2. the array that contains the data. Again, this can be done for as many arrays as needed.
  • Of course, the preRegister functionality can be used for any kind of variables or arrays, no matter whether you have saved a rendered template (like in our example) into it or it contains just a simple boolean true/false statement.
To access the data inside the template it was preregistered for use:
HTML Code:
{vb:raw my_insertvar}
Note: it is not {vb:raw templatevalues.my_insertvar}!

Essentially the same as what I put for preRegister would be the following two lines. They could replace the last two lines in the above php codebox:
PHP Code:
$my_insertvar $templater->render();
vB_Template::preRegister('FORUMHOME',array('my_insertvar ' => $my_insertvar)); 
Of course you could add further pairs to that array if you need to preregister more than one variable.
.
.
Bonus track: ...whatever you do, cache your templates!

Now you know how to get your templates on screen - once you succeeded in doing that, make sure to do it in a fast and ressource saving manner: make use of vB's template cache. To see whether your templates are cached or not, activate debug mode by adding $config['Misc']['debug'] = true;to your config.php (don't ever use that on your live site!). Among the debug info is a list of all templates called, and non-cached templates will show up in red.

To cache your templates, add a plugin at hook cache_templates with the following code:
PHP Code:
// for a single template
$cache[] = 'mytemplate'

// for more than one templates in one step
$cache array_merge((array)$cache,array(
    
'mytemplate',
    
'myothertemplate',
    
'mythirdtemplate'
)); 
.
.
Hope this helps!
-cel

----
Addendum - There are now two blog posts on vb.com related to this topic:
http://www.vbulletin.com/forum/entry...in-4-templates
http://www.vbulletin.com/forum/entry...-4-based-files
Reply With Quote
  #262  
Old 12-26-2012, 04:51 PM
BirdOPrey5's Avatar
BirdOPrey5 BirdOPrey5 is offline
Senior Member
 
Join Date: Jun 2008
Location: New York
Posts: 10,610
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

What error are you getting?
Reply With Quote
  #263  
Old 12-26-2012, 05:12 PM
acast acast is offline
 
Join Date: Aug 2008
Posts: 179
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

Quote:
Originally Posted by BirdOPrey5 View Post
What error are you getting?
I don't know what exactly is the problem, in this case, is like the things aren't well connected. When i put hangman.php in 3.6, automatically add to the direction "?n=1" and if i clikc in the letters the program run well, but in 4 didn't do it. Also, in other plugin i have a button, but if i click it doesn't go to anywhere.

My question is: if you register a variable that doesn't have to be register, the php makes an error? I did this in the plugin:
Code:
$templater = vB_Template::create('hangman');
$templater->register_page_templates();
$templater->register('hangmanwords', $hangmanwords);
$templater->register('hangmanmax', $hangmanmax);
$templater->register('hangmanguests', $hangmanguests);
$templater->register('letters', $letters);
$templater->register('n', $n);
$templater->register('additional_letters', $additional_letters);
$templater->register('words', $words);
$templater->register('alpha', $alpha);
$templater->register('all_letters', $all_letters);
$templater->register('wrong', $wrong);
$templater->register('word', $word);
$templater->register('done', $done);
$templater->register('word_line', $word_line);
$templater->register('c', $c);
$templater->register('links', $links);
$templater->register('max', $max);
$templater->register('x', $x);
$templater->register('sorry', $sorry);
$templater->register('play', $play);
$templater->register('win', $win);
$templater->register('term', $term);
$templater->register('guess', $guess);
$templater->register('nwrong', $nwrong);
$templater->register('navbar', $navbar);
$templater->register('pagetitle', $pagetitle);
print_output($templater->render());
but i don't know if all these variables must to be put it like this.

Sorry for my english, and thanks for your help. Also, the plugin, if you want to see it something more of the code is here:
https://vborg.vbsupport.ru/showthrea...hlight=hangman
Reply With Quote
  #264  
Old 12-26-2012, 05:25 PM
Lynne's Avatar
Lynne Lynne is offline
 
Join Date: Sep 2004
Location: California/Idaho
Posts: 41,180
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

Can you post your hangman template code?
Reply With Quote
  #265  
Old 12-26-2012, 05:34 PM
acast acast is offline
 
Join Date: Aug 2008
Posts: 179
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

Quote:
Originally Posted by Lynne View Post
Can you post your hangman template code?
Hi Lynne

The original template hangman:
Code:
$stylevar[htmldoctype]
<html dir="$stylevar[textdirection]" lang="$stylevar[languagecode]">
<html>
<head>
<meta name="description" content="$foruminfo[description]" />
<title>$vboptions[bbtitle] - $vbphrase[vb_hangman]</title>
$headinclude
</head>
<body>
$header
$navbar 
<br>
<table class="tborder" cellpadding="0" cellspacing="0" border="0" bgcolor="0" width="100%" align="center"><tr><td>
<table cellpadding="$stylevar[cellpadding]" cellspacing="0" border="0" width="100%">
<tr id="cat">
	<td bgcolor="{categorybackcolor}" colspan="5" class="tcat"><b> $vbphrase[vb_hangman]</b>
</td>
</tr>
<table cellpadding="$stylevar[cellpadding]" cellspacing="$stylevar[cellspacing]" border="0" width="100%">

          <td class="alt1"> 
<br>
</div>
            <center>
<p>
<img src="images/hangman/hangman_$nwrong.gif" align="absmiddle" border="0" height="100" width="100" alt="Wrong: $wrong out of $max">
</p>
$sorry $play $guess $win
<br><br><br>
            </center>
</tr>
</td>
<tr>
	<td class="tfoot">
&nbsp;
</td>
</tr>
</table>
</table>
</td></tr></table>
$footer 
</body>
</html>
My modified template:
Code:
{vb:stylevar htmldoctype}
<html dir="{vb:stylevar textdirection}" lang="{vb:stylevar languagecode} id="vbulletin_html">
<html>
<head>

<title>{vb:raw vboptions.bbtitle} - {vb:raw pagetitle}</title>
{vb:raw headinclude}
</head>
<body>
{vb:raw header}
{vb:raw navbar}
<br>
<table class="tborder" cellpadding="0" cellspacing="0" border="0" bgcolor="0" width="100%" align="center"><tr><td>
<table cellpadding="{vb:stylevar cellpadding}" cellspacing="0" border="0" width="100%">
<tr id="cat">
	<td bgcolor="{categorybackcolor}" colspan="5" class="tcat"><b> {vb:raw phrase vb_hangman}</b>
</td>
</tr>
<table cellpadding="{vb:stylevar cellpadding}" cellspacing="{vb:stylevar cellspacing}" border="0" width="100%">

          <td class="alt1"> 
<br>
</div>
            <center>
<p>
<img src="images/hangman/hangman_{vb:raw nwrong}.gif" align="absmiddle" border="0" height="100" width="100" alt="Wrong: {vb:raw wrong} out of {vb:raw max}">
</p>
{vb:raw sorry} {vb:raw play} {vb:raw guess} {vb:raw win}
<br><br><br>
            </center>
</tr>
</td>
<tr>
	<td class="tfoot">
&nbsp;
</td>
</tr>
</table>
</table>
</td></tr></table>
{vb:raw footer}
</body>
</html>
Thanks for your help too. This plugin is not important for me, but i want to learn so i can do it in other ones more important
Reply With Quote
  #266  
Old 12-27-2012, 12:04 AM
Lynne's Avatar
Lynne Lynne is offline
 
Join Date: Sep 2004
Location: California/Idaho
Posts: 41,180
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

The template looks OK.... I don't see a link to the page so we can see exactly what is happening. Something can "not work" in so many different ways, so it would be good to see exactly what is going on with this one.
Reply With Quote
  #267  
Old 12-27-2012, 07:16 AM
acast acast is offline
 
Join Date: Aug 2008
Posts: 179
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

Quote:
Originally Posted by Lynne View Post
The template looks OK.... I don't see a link to the page so we can see exactly what is happening. Something can "not work" in so many different ways, so it would be good to see exactly what is going on with this one.
Ok, i'll send you now a private message with the login to my forum. If somebody wants it too, tell me.


This is another plugin where i have, apparently, the same problem:
The code is in the attached txt.


Thank you for your help again. I reall apreciate always your help Lynne.
Attached Files
File Type: txt code.txt (52.7 KB, 6 views)
Reply With Quote
  #268  
Old 12-27-2012, 03:28 PM
BirdOPrey5's Avatar
BirdOPrey5 BirdOPrey5 is offline
Senior Member
 
Join Date: Jun 2008
Location: New York
Posts: 10,610
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

Registering a variable that doesn't need to be registered or is empty will NOT cause an error.

Are you just getting a blank white page when you try to view it? In that case look for your php error log (your host may be able to tell you how to view it) and see what errors are coming up after trying to view the blank page.
Reply With Quote
  #269  
Old 12-27-2012, 03:38 PM
acast acast is offline
 
Join Date: Aug 2008
Posts: 179
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

Quote:
Originally Posted by BirdOPrey5 View Post
Registering a variable that doesn't need to be registered or is empty will NOT cause an error.

Are you just getting a blank white page when you try to view it? In that case look for your php error log (your host may be able to tell you how to view it) and see what errors are coming up after trying to view the blank page.
Thank you for the answer. I sent you also the links for if you want to take a look.

Also i have another question of the use in the templates. For example, in the code that i put, in the old one appears like this:
Code:
<vb:if condition="$stocktable != null">
That is right for the templates?

--------------- Added [DATE]1356642316[/DATE] at [TIME]1356642316[/TIME] ---------------

I solve the problem of the hangman. It seems like the PHP_SELF doesn't work in v4. Thanks to Lynne for the help.

But i am working in the other one. My previous question to BirdOprey5 is about it.

Lynne suspect that perhaps the problem is about javascript/ajax. ?Is different to v3 to v4?

This is the code, if somebody knows that it is right or wrong:

Code:
//-----------------------------------------------------------------------------
// $Workfile: vbulletin_ajax_stocktrader.js $ $Revision: 1.4 $ $Author: addy $ 
// $Date: 2007/01/02 03:31:59 $
//-----------------------------------------------------------------------------

var stock_xml;

function handle_stock_lookup(symbol)
{
	stock_xml = new vB_AJAX_Handler(true);
	stock_xml.onreadystatechange(handle_stock_lookup_response);
	stock_xml.send('vbtrade.php?do=lookup&symbol=' + symbol);
	
	return false;
}

function handle_stock_lookup_response()
{
	if (stock_xml.handler.readyState == 4 && stock_xml.handler.status == 200)
	{
		if (stock_xml.handler.responseXML)
		{
			var response = stock_xml.fetch_data(fetch_tags(stock_xml.handler.responseXML, 'tag1')[0]);
			if (response != null)
			{	
				var lookup_table = null;
				
				if (document.getElementById)
					lookup_table = document.getElementById('lookup_table');

				if (lookup_table)
					lookup_table.innerHTML = response;
			}
		}
	}
}
Thanks if anybody can take a look to it and verify that it is right.
Reply With Quote
  #270  
Old 12-29-2012, 07:43 PM
BirdOPrey5's Avatar
BirdOPrey5 BirdOPrey5 is offline
Senior Member
 
Join Date: Jun 2008
Location: New York
Posts: 10,610
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

Code:
<vb:if condition="$stocktable != null">
That looks allowed in VB4 template, of course it need an ending </vb:if> somewhere.

I'm sorry I don't know anything about AJAX differences between VB3 and VB4.
Reply With Quote
  #271  
Old 12-30-2012, 08:22 AM
acast acast is offline
 
Join Date: Aug 2008
Posts: 179
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

Quote:
Originally Posted by BirdOPrey5 View Post
Code:
<vb:if condition="$stocktable != null">
That looks allowed in VB4 template, of course it need an ending </vb:if> somewhere.

I'm sorry I don't know anything about AJAX differences between VB3 and VB4.
Thanks, it doesn't seem to be anything about ajax. I put it the problem here:
https://vborg.vbsupport.ru/showthrea...=242454&page=7

That variable "stocktable" must be registered in a plugin, but if i do it the forum dissapears.
Reply With Quote
Reply


Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT. The time now is 03:20 PM.


Powered by vBulletin® Version 3.8.12 by vBS
Copyright ©2000 - 2024, vBulletin Solutions Inc.
X vBulletin 3.8.12 by vBS Debug Information
  • Page Generation 0.12479 seconds
  • Memory Usage 2,403KB
  • Queries Executed 26 (?)
More Information
Template Usage:
  • (1)SHOWTHREAD
  • (1)ad_footer_end
  • (1)ad_footer_start
  • (1)ad_header_end
  • (1)ad_header_logo
  • (1)ad_navbar_below
  • (1)ad_showthread_beforeqr
  • (7)bbcode_code
  • (3)bbcode_html
  • (10)bbcode_php
  • (5)bbcode_quote
  • (1)footer
  • (1)forumjump
  • (1)forumrules
  • (1)gobutton
  • (1)header
  • (1)headinclude
  • (1)modsystem_article
  • (1)navbar
  • (4)navbar_link
  • (120)option
  • (1)pagenav
  • (1)pagenav_curpage
  • (4)pagenav_pagelink
  • (1)pagenav_pagelinkrel
  • (11)post_thanks_box
  • (17)post_thanks_box_bit
  • (11)post_thanks_button
  • (1)post_thanks_javascript
  • (1)post_thanks_navbar_search
  • (1)post_thanks_postbit
  • (11)post_thanks_postbit_info
  • (10)postbit
  • (1)postbit_attachment
  • (11)postbit_onlinestatus
  • (11)postbit_wrapper
  • (1)spacer_close
  • (1)spacer_open
  • (1)tagbit_wrapper 

Phrase Groups Available:
  • global
  • inlinemod
  • postbit
  • posting
  • reputationlevel
  • showthread
Included Files:
  • ./showthread.php
  • ./global.php
  • ./includes/init.php
  • ./includes/class_core.php
  • ./includes/config.php
  • ./includes/functions.php
  • ./includes/class_hook.php
  • ./includes/modsystem_functions.php
  • ./includes/functions_bigthree.php
  • ./includes/class_postbit.php
  • ./includes/class_bbcode.php
  • ./includes/functions_reputation.php
  • ./includes/functions_post_thanks.php 

Hooks Called:
  • init_startup
  • init_startup_session_setup_start
  • init_startup_session_setup_complete
  • cache_permissions
  • fetch_threadinfo_query
  • fetch_threadinfo
  • fetch_foruminfo
  • style_fetch
  • cache_templates
  • global_start
  • parse_templates
  • global_setup_complete
  • showthread_start
  • showthread_getinfo
  • forumjump
  • showthread_post_start
  • showthread_query_postids
  • showthread_query
  • bbcode_fetch_tags
  • bbcode_create
  • showthread_postbit_create
  • postbit_factory
  • postbit_display_start
  • post_thanks_function_post_thanks_off_start
  • post_thanks_function_post_thanks_off_end
  • post_thanks_function_fetch_thanks_start
  • fetch_musername
  • post_thanks_function_fetch_thanks_end
  • post_thanks_function_thanked_already_start
  • post_thanks_function_thanked_already_end
  • post_thanks_function_fetch_thanks_bit_start
  • post_thanks_function_show_thanks_date_start
  • post_thanks_function_show_thanks_date_end
  • post_thanks_function_fetch_thanks_bit_end
  • post_thanks_function_fetch_post_thanks_template_start
  • post_thanks_function_fetch_post_thanks_template_end
  • postbit_imicons
  • bbcode_parse_start
  • bbcode_parse_complete_precache
  • bbcode_parse_complete
  • postbit_display_complete
  • post_thanks_function_can_thank_this_post_start
  • postbit_attachment
  • pagenav_page
  • pagenav_complete
  • tag_fetchbit_complete
  • forumrules
  • navbits
  • navbits_complete
  • showthread_complete