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
  #292  
Old 04-01-2014, 05:22 PM
Kestryll Kestryll is offline
 
Join Date: Nov 2006
Posts: 27
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

I do have a test site up with a separate database and vB install on it for testing prior to trying anything on my live forum.

You'll have to excuse my manner of asking follow up questions, when I can't get something to work I tend to ask questions in the form of clarification of what I am doing assuming I have made an error rather than saying 'that didn't work'. It seems more respectful of those trying to help.
The comment about roasting my vB install is mostly comedy however I did manage to do something to my test install when I first tried to make the ad banners work that killed it and required a wipe and reinstall.

So far I have not been able to get the random banners to display, all I have gotten is the header code displaying above the title.
I have placed the header code in various places within the header template and have placed the registration code at the very end of the plug in as above and tried it as the second line of the plug in.
All with the same results, I can only assume that I am missing a step somewhere.
Reply With Quote
  #293  
Old 04-01-2014, 10:17 PM
Lynne's Avatar
Lynne Lynne is offline
 
Join Date: Sep 2004
Location: California/Idaho
Posts: 41,180
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

I couldn't tell from your post whether you were asking for help or not. But, I did just notice that you have the variable entered wrong in your template (that's what happens when you look at vB3 and vB4 and vB5 sites all the time!). It's

{vb:raw random_banner11['$random_number11']}

And, I didn't notice you had two variables - you need to register each of them.
Reply With Quote
  #294  
Old 05-16-2014, 05:06 PM
Lynne's Avatar
Lynne Lynne is offline
 
Join Date: Sep 2004
Location: California/Idaho
Posts: 41,180
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

The first post shows you how to register a variable here:
PHP Code:
$my_insertvar $templater->render();
vB_Template::preRegister('FORUMHOME',array('my_insertvar ' => $my_insertvar)); 
That registers the variable $my_insertvar to be used in the template FORUMHOME. Go back and relook at the article and you will see this explained.
Reply With Quote
  #295  
Old 05-18-2014, 04:24 PM
Lynne's Avatar
Lynne Lynne is offline
 
Join Date: Sep 2004
Location: California/Idaho
Posts: 41,180
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

Quote:
Originally Posted by semprot View Post
so i need to type that code on all PHP files on root? (usercp.php, forum.php, etc ?)
No, you can add it to a plugin. If you are using it on every page, then you'll want to use a hook location that is on every page - maybe one of the global_* ones. You'll have to try it and see which works best.
Reply With Quote
Благодарность от:
  #296  
Old 11-29-2014, 12:59 PM
npadbidri npadbidri is offline
 
Join Date: Nov 2014
Posts: 11
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

Hi,

I understand above all things. I just wanted to know that,
{vb:raw user.username}
above code I found in template 'header'.
From where this header template gets object 'user' and how it can able to access it property.

I am interested know where this vBulletin variable like 'user' stored and in which php file?

Can any one help me to understand this?

Thanks!!!!
Reply With Quote
  #297  
Old 11-29-2014, 05:12 PM
Lynne's Avatar
Lynne Lynne is offline
 
Join Date: Sep 2004
Location: California/Idaho
Posts: 41,180
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

Quote:
Originally Posted by npadbidri View Post
Hi,

I understand above all things. I just wanted to know that,
{vb:raw user.username}
above code I found in template 'header'.
From where this header template gets object 'user' and how it can able to access it property.

I am interested know where this vBulletin variable like 'user' stored and in which php file?

Can any one help me to understand this?

Thanks!!!!
The header template is rendered in the /includes/class_bootstrap.php file around line 509. So, try looking at the code above there. (But, I don't see any $user variable registered for use in that template, nor do I see the template code "{vb:raw user.username}" being used in the header template. If you do see that, then this may be from a modification.)
Reply With Quote
  #298  
Old 02-01-2015, 09:08 AM
TheAdminMarket's Avatar
TheAdminMarket TheAdminMarket is offline
 
Join Date: Jun 2013
Location: Thessaloniki, Greece
Posts: 511
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

Any suggestion why the code below does not works as expected?
PHP Code:
<plugin active="1" executionorder="20">
    <
title>Build Advertisments Block</title>
    <
hookname>cache_templates</hookname>
    <
phpcode><![CDATA[
        global 
$db$vbulletin;
        
$group $vbulletin->db->query_first("SELECT * FROM ".TABLE_PREFIX."banners_groups WHERE active=1 ORDER BY lastshow ASC LIMIT 1");
        
$groupid $group["id"];
        
$spots $group["spots"];
        
$random $group["random"];
        
$cellwidth 100/$spots;
        
// Update Group with Last Show Time
        
$timenow time();
        
$vbulletin->db->query_write("UPDATE ".TABLE_PREFIX."banners_groups SET lastshow=$timenow WHERE id=$groupid ORDER BY id ASC");
        
// List Group Advertisments
        
if ($random == 1)
        {
            
$advertisments $vbulletin->db->query_read("SELECT * FROM ".TABLE_PREFIX."banners_advertisers WHERE groupid=$groupid AND active=1 ORDER BY rand() LIMIT $spots");
        } else {
            
$advertisments $vbulletin->db->query_read("SELECT * FROM ".TABLE_PREFIX."banners_advertisers WHERE groupid=$groupid AND active=1 ORDER BY displayorder ASC LIMIT $spots");
        }
        
$main_bit '';
        while (
$advertisment $vbulletin->db->fetch_array($advertisments)) {
            
// Prepare Templates
            
$templater vB_Template::create('banners_main_bit');
            
$templater->register('htmlcode'htmlspecialchars_uni($advertisment[htmlcode]));
            
$templater->register('cellwidth'$cellwidth);
            
$main_bit .= $templater->render();
        }
        
$templater vB_Template::create('banners_main');
        
$templater->register('main_bit'$main_bit);
        
$templatevalues['mybanners'] = $templater->render();
        
vB_Template::preRegister('header'$templatevalues);
    ]]></
phpcode>
</
plugin
Taking in account that:
  1. I used many different hooks like: global_start, global_complete, fetch_templates etc.
  2. I also used many different templates like: ad_global_header1 etc
  3. The same code with only difference the last 2 lines is working in php file if I use: print_output($templater->render());
Thank you very much

EDIT: What I was adding in the templates is: {vb:raw mybanners}
Reply With Quote
  #299  
Old 02-01-2015, 11:53 AM
kh99 kh99 is offline
 
Join Date: Aug 2009
Location: Maine
Posts: 13,185
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

I would use hook parse_templates. You say you've tried "many different templates", do you mean other hean 'header'? Of course you know, but double check that you put {vb:raw mybanners} in the same template that you preRegister() to.
Reply With Quote
Благодарность от:
TheAdminMarket
  #300  
Old 02-01-2015, 01:35 PM
TheAdminMarket's Avatar
TheAdminMarket TheAdminMarket is offline
 
Join Date: Jun 2013
Location: Thessaloniki, Greece
Posts: 511
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

Quote:
Originally Posted by kh99 View Post
I would use hook parse_templates. You say you've tried "many different templates", do you mean other hean 'header'? Of course you know, but double check that you put {vb:raw mybanners} in the same template that you preRegister() to.
hmm... Didn't tried that hook and sounds matching the case. As for the rest. Except a typo that I had at the very begining (ad_global_header_1 instead ad_global_header1), the other were correct. And yes I tried many templates, even custom ones from my addons. So:
  1. Difficult to be the template name or the content as the variable is correct.
  2. PHP code is correct as it works with a test file that I did.
After all the hook must be wrong. Let's try with yours

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

Quote:
Originally Posted by kh99 View Post
I would use hook parse_templates.
That did the trick. Thank you.
Reply With Quote
  #301  
Old 02-20-2015, 03:13 PM
Easy5s.net Easy5s.net is offline
 
Join Date: Jun 2011
Posts: 201
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

hock process_templates_complete

PHP Code:
$templater vB_Template::create('testtest');
    
$templater->register('var1'$var1);
    
$templater->register('var2'$var2);
$out[test] = $templater->render();
$ad_location['global_below_navbar'] .= $out
but not work???. I want auto add temp to below navbar.
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 09:37 AM.


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.09810 seconds
  • Memory Usage 2,410KB
  • 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
  • (3)bbcode_html
  • (13)bbcode_php
  • (4)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
  • (3)pagenav_pagelink
  • (1)pagenav_pagelinkrel
  • (11)post_thanks_box
  • (18)post_thanks_box_bit
  • (11)post_thanks_button
  • (1)post_thanks_javascript
  • (1)post_thanks_navbar_search
  • (3)post_thanks_postbit
  • (11)post_thanks_postbit_info
  • (10)postbit
  • (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
  • pagenav_page
  • pagenav_complete
  • tag_fetchbit_complete
  • forumrules
  • navbits
  • navbits_complete
  • showthread_complete