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
  #172  
Old 07-20-2011, 02:53 AM
Murtific Murtific is offline
 
Join Date: Jul 2011
Posts: 28
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

Quote:
Originally Posted by HMBeaty View Post
Just paste your code you're using inside code/html/php tags. For example:

[code.]your code here[./code]
Would be
Code:
your code here
[php.]your code here[./php]
Would be
PHP Code:
your code here 
[html.]your code here[./html]
Would be
HTML Code:
your code here
Obviously without the "." in the tags though
Thanks, got it. Now back to my previous post, anybody have any ideas?
Reply With Quote
  #173  
Old 07-20-2011, 11:34 AM
BirdOPrey5's Avatar
BirdOPrey5 BirdOPrey5 is offline
Senior Member
 
Join Date: Jun 2008
Location: New York
Posts: 10,610
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

What hook is your code on?
Reply With Quote
  #174  
Old 07-20-2011, 02:32 PM
Murtific Murtific is offline
 
Join Date: Jul 2011
Posts: 28
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

what's a hook? I dont have a hook. I ended up just doing this. I basically just added my database code to the forum.php file and got it to work, but i have to modify every template like I mentioned in this thread, i'd rather use this thread https://vborg.vbsupport.ru/showthread.php?t=267120
Reply With Quote
  #175  
Old 07-20-2011, 03:20 PM
kh99 kh99 is offline
 
Join Date: Aug 2009
Location: Maine
Posts: 13,185
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

Quote:
Originally Posted by Murtific View Post
what's a hook? I dont have a hook. I ended up just doing this. I basically just added my database code to the forum.php file and got it to work,
[S]That's probably the issue - if you put it in after global.php, it's too late to affect the header[/S]. (Edit: actually that's wrong, I think you have until another template is rendered, so what you did could have worked, but try it with a plugin anyway.)

See my post in the other thread.
Reply With Quote
  #176  
Old 07-23-2011, 04:36 PM
Dave-ahfb Dave-ahfb is offline
 
Join Date: Mar 2002
Posts: 117
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

First let me say that I am not PHP literate, but can find my way around 9 times out of 10.

I am creating custom templates to include my non vb scripts but am having troubles when trying to include a variable(?) from this script in any template outside the main body.

I will try to be as detailed as possible, hopefully any responses will include the information I give as a real life example so that I can get an understanding of what was done.


Goal: to take $companyname from the below script and add it to my page title, navbits etc. (currently I only get echos of $companyname or {vb:raw companyname}, depending on where I am in my efforts.
PHP Code:
if (isset($_GET['company']))
    
$company $_GET['company'];
   else
    
$company '100megs';
$result mysql_query("select * from hostwebhost where companyname = '$company'");
if (!
$result) {
$numrows 0;
} else {
$numrows mysql_num_rows($result);
}
for(
$x=0;$x<$numrows;$x++){
while (
$row mysql_fetch_array($result)){
$host_id $row[0];
$companyname $row[1];
$emailaddress $row[2]; 
$URL $row[3]; 
$track $row[4]; 
$imgtop $row[5]; 
$imgright $row[6]; 
$imgbody $row[7]; 
$joined $row[8]; 
$password $row[9]; 
$isvalid $row[10]; 
$supportlist $row[11]; 
$street1 $row[12]; 
$street2 $row[13]; 
$city $row[14]; 
$state $row[15]; 
$zip $row[16]; 
$country $row[17]; 
$contactname $row[18]; 
$contactphone $row[19]; 
$contactfax $row[20]; 
$suggested $row[21]; 
$comdescrip $row[22]; 
$registered $row[23]; 
plugin info:
PHP Code:
locationglobal_bootstrap_init_start
title
Webhost-php Include
execution order5
code
:
ob_start();
ob_start();
include(
'/srv/www/findnewhosting.com/public_html/webhost1.php');
$webhost ob_get_contents();
ob_end_clean(); 
vB_Template::preRegister('webhost-php', array('webhost' => $webhost)); 
As you can see the script is webhost1.phpwhich includes the first set of code above. Please note that the custom page is webhost.php which contains the following:
PHP Code:
<?php

// ####################### SET PHP ENVIRONMENT ###########################
error_reporting(E_ALL & ~E_NOTICE);

// #################### DEFINE IMPORTANT CONSTANTS #######################

define('THIS_SCRIPT''webhosting');
define('CSRF_PROTECTION'true);  
// change this depending on your filename

// ################### PRE-CACHE TEMPLATES AND DATA ######################
// get special phrase groups
$phrasegroups = array();

// get special data templates from the datastore
$specialtemplates = array();

// pre-cache templates used by all actions
$globaltemplates = array('webhost-php',);

// pre-cache templates used by specific actions
$actiontemplates = array();

// ######################### REQUIRE BACK-END ############################
chdir ('/srv/www/findnewhosting.com/public_html');

require_once(
'/srv/www/findnewhosting.com/public_html/global.php');

// #######################################################################
// ######################## START MAIN SCRIPT ############################
// #######################################################################

$navbits construct_navbits(array('' => '&nbsp;</span></li><li class="navbit"><span><a href="/">Home</a></span></li><li class="navbit"><span><a href="../hostindex.php">Web Hosting</a></span></li><li class="navbit lastnavbit"><span>{vb:raw companyname} 

'
));
$navbar render_navbar_template($navbits);

// ###### YOUR CUSTOM CODE GOES HERE #####
$pagetitle '$companyname';
$templater vB_Template::create('headerincludea');
$headerincludea $templater->render();
$templater vB_Template::create('webhost-php');
$templater->register_page_templates();
$templater->register('navbar'$navbar);
$templater->register('pagetitle'$pagetitle);
$templater->register('sidebarext'$sidebarext);
$templater->register('sidebaropen'$sidebaropen);
$templater->register('headerincludea'$headerincludea);


print_output($templater->render());
?>
webhost-php(template):
PHP Code:
{vb:stylevar htmldoctype}
<
html xmlns="http://www.w3.org/1999/xhtml" dir="{vb:stylevar textdirection}" lang="{vb:stylevar languagecode}" id="vbulletin_html">
<
head>
<
title>{vb:raw companyname}</title>
{
vb:raw headerincludea}
{
vb:raw headinclude_bottom}
</
head>
<
body>
{
vb:raw header}
{
vb:raw navbar}
{
vb:raw sidebaropen}
<
br />
<
div id="pagetitle">
<
h1>&nbsp;&nbsp;{vb:raw pagetitle}</h1><br />
</
div>
<
div class="blockbody">
<
div class="blockrow">
<
div align="center">

{
vb:raw webhost}

</
div>
</
div>
</
div>
    {
vb:raw sidebarext}


    {
vb:raw footer}
  </
body>
</
html
If there is any other info I can give to make it easier to solve just let me know.

Dave
Reply With Quote
  #177  
Old 07-23-2011, 05:30 PM
BirdOPrey5's Avatar
BirdOPrey5 BirdOPrey5 is offline
Senior Member
 
Join Date: Jun 2008
Location: New York
Posts: 10,610
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

I don't know if it's your only problem but you didn't register $companynanme in your webhost1.php file, so it won't show in your template.
Reply With Quote
  #178  
Old 07-23-2011, 05:48 PM
Dave-ahfb Dave-ahfb is offline
 
Join Date: Mar 2002
Posts: 117
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

Could you dumb that down please?
Reply With Quote
  #179  
Old 07-24-2011, 12:50 PM
BirdOPrey5's Avatar
BirdOPrey5 BirdOPrey5 is offline
Senior Member
 
Join Date: Jun 2008
Location: New York
Posts: 10,610
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

Quote:
Originally Posted by Dave-ahfb View Post
Could you dumb that down please?
At the end of webhost1.php you have this code:

Code:
$templater = vB_Template::create('webhost-php'); 
$templater->register_page_templates(); 
$templater->register('navbar', $navbar); 
$templater->register('pagetitle', $pagetitle); 
$templater->register('sidebarext', $sidebarext); 
$templater->register('sidebaropen', $sidebaropen); 
$templater->register('headerincludea', $headerincludea); 


print_output($templater->render());
You need to add this line:

Code:
$templater = vB_Template::create('webhost-php'); 
$templater->register_page_templates(); 
$templater->register('navbar', $navbar); 
$templater->register('pagetitle', $pagetitle); 
$templater->register('sidebarext', $sidebarext); 
$templater->register('sidebaropen', $sidebaropen); 
$templater->register('headerincludea', $headerincludea); 
$templater->register('companynanme', $companynanme);

print_output($templater->render());
ALL variables you need to use in a template MUST be registered to a template before you use it. If you use any other variables you must register them also.
Reply With Quote
  #180  
Old 07-24-2011, 02:26 PM
Dave-ahfb Dave-ahfb is offline
 
Join Date: Mar 2002
Posts: 117
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

Thank you so much. As soon as I can put this paint brush down I will give it a shot.

Dave
Reply With Quote
  #181  
Old 07-26-2011, 05:19 PM
heugabel heugabel is offline
 
Join Date: May 2006
Posts: 74
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

Code:
	$search_text = '<!-- end logged-in users -->';
	$vbulletin->templatecache['FORUMHOME'] = str_replace($search_text, $search_text . fetch_template('forumhome_xyz'), $vbulletin->templatecache['FORUMHOME']);
how i can rewrite this for vb4?

thank you
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 08:08 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.07947 seconds
  • Memory Usage 2,433KB
  • 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
  • (4)bbcode_code
  • (4)bbcode_html
  • (15)bbcode_php
  • (3)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
  • (2)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
  • (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