How can I use a Smarty template from a Smarty template? - php

I've run into a funny problem. I need to use Smarty templates within a Smarty template.
Here is why. I use the same templates for various wiki websites, and each website has its own configuration. The configuration contains parts for the main template (such as changed titles and headings, etc).
Here is a simplified example. I've a file topic-list.template.html that's shared across all websites:
<div id="topics">
<h1>{$h1}</h1>
...
</div>
As you can see, this template file contains an <h1> tag that can be customized for each website.
Then for each of the websites I've a configuration file that looks like this (simplified):
$config = [
"h1-titles" => [
"topics" => "Showing Topics in {\$category}"
]
];
As you can see the configuration file contains a Smarty template.
So when I render the topic-list.template.html file, I've to render the $config['h1-titles']['topics'] first through $smarty->fetch("string":$config['h1-titles']['topics']), and then assign it to h1 Smarty variable. My simplified code looks like this:
$h1_tag = $smarty->fetch("string":$config['h1-titles']['topics']);
$smarty->assign('h1', $h1_tag);
$smarty->display('topic-list.template.html');
I wonder if I could somehow insert the $config['h1-titles']['topics'] in the topic-list.template.html file automatically and then it have all rendered in one go?

Please have a look at the docs on String Template Resources. You will immediately notice that your $smarty->fetch('string:…') approach can also be done within a template: {include file="string:…"}

I believe that {eval} tag may help you:
{eval} is used to evaluate a variable as a template. This can be used for things like embedding template tags/variables into variables or tags/variables into config file variables.
http://www.smarty.net/docs/en/language.function.eval.tpl

Related

Including PHP file inside smarty template file

I have completely no idea about smarty template system. What I am trying to do is include a php file to get some variable inside a .tpl file (this is a WHMCS template).
I have tried like:
{php} include ('file.php'); {/php} //doesn't work
{include_php file='file.php'} //doesn't work
I have also followed the answer of this question. Still couldn't get it working.
How can I include code.php inside header.tpl of WHMCS? Any help please?
Just for reference: both tpl and php file is in the same directory, if that helps anyway.
It's really not recommended to use php code in Smarty. In fact it's now deprecated and you should avoid such solution as much as possible because it often doesn't have sense.
However if you really want to use PHP in your Smarty files for some reason you need to use SmartyBC (Smarty Backward Compatibility) class instead of Smarty class.
So for example instead of:
require_once(_PS_SMARTY_DIR_.'Smarty.class.php');
$smarty = new Smarty();
you should use:
require_once('SmartyBC.class.php');
$smarty = new SmartyBC();
Then you will be able to use PHP in your Smarty template files
EDIT
If you have just problem with including it's probably your directories problem (however you haven't showed any errors).
I assume you have your files inside your templates directory and you set it properly using:
$smarty->setTemplateDir('templates');
if you simple display index.tpl file in Smarty and you have this PHP file in the same directory (in template directory) you can include it without a path.
However if you include in this index.tpl file another tpl file, when you want to include php file you need to pass the full path to this PHP file, for example:
{include_php 'templates/file.php''}
Your using Smarty the wrong way. The whole point of Smarty is to NOT include any PHP in your presentation bits (views, a.k.a. the good ol' HTML).
So, whatever you're trying to do in that PHP file, just let it do its magic, but send the actual result to Smarty. For example, do you want to show a table of users you get out of a database? Execute the query, fetch the result and pass the results (like an array of results) to smarty like this:
<?php
$smarty = new Smarty();
$users = $db->query('SELECT * FROM users');
// Assign query results to template file.
$smarty->assign('users', $users);
// Compile and display the template.
$smarty->display('header.tpl');
Now, in your smarty template you can access that array like this:
<html>
{foreach from=$users item=user}
Username: {$user->username}<br />
{/foreach}
</html>
I hope you see where I am going. Keep your application logic in the PHP file, and let the template just take care of the looks. Keep the template as dumb as possible!
You get data into Smarty by assigning it. Embedding PHP is not recommended, and deprecated from Smarty 3.
php:
$smarty->assign('foo','bar');
smarty:
{$foo}

Cakephp splitting long view.ctp into smaller ones

One of my view file in cake is getting very long, like 300+ lines already. And i find it very difficult to keep track of the understanding.
Is it a good idea to split them up into smaller files and then including them in the parent view file?
If its ok to be done,
In what extension should i create the smaller files? .ctp or .php?
Including them with require_once(view-child1.ext) should be fine, right?
Im fairly new to cakePHP. So i prefer advises from the experts over here. Please put me in the right direction.
EDIT
Thanks for the help guys.
I tried it. But i cant seem to pass the variable. echo $this->Element('reviews/view-goal',$history); Parent view shows and error saying undefined variable in that element.
Im calling the elements from this loop:
foreach($histories as $date => $history)
Cant pass $history. But $histories is being passed correctly.
You should make elements in View/Elements folder with .ctp extension.
This link would help you to make clean separation of your view files with the related/repeated code.
An element is basically a mini-view that can be included in other views, in layouts, and even within other elements. Elements can be used to make a view more readable, placing the rendering of repeating elements in its own file. They can also help you re-use content fragments in your application.
Elements live in the /app/View/Elements/ folder, and have the .ctp filename extension. They are output using the element method of the view:
<?php echo $this->element('helpbox'); //without extension ?>
You can pass variables from your view to the element.
In your view:
<?php echo $this->Element('reviews/view-goal', array('history' => $history));
In view-goal.ctp element you can directly access $history variable.
Yes, it is a very good idea. But don't use the normal require() of PHP.
CakePHP has a feature called "elements", a mechanism to put parts of a view into separate .ctp files. The files go in a special folder, View/Elements
You can include an element like this:
echo $this->element('sidebar/recent_comments');
If you need any variables inside the element, you need to pass them in an additional array parameter:
echo $this->element('sidebar/recent_comments', array('variable_name' => /* Variable content */));
In order to keep your view files small, you should also make sure that you put stuff that is shared by most pages (header, footer) into the Layout file. And obviously: keep JS and CSS in external files.

CodeIgniter "Template" system

Whenever I start a new project I find myself remaking and rethinking my self made template library. I use some influences from dom manipulation, but don't want to make too much functions so that it still loads fast.
This is how my current template system looks like:
This is a layout file:
<body>
<div id="content">
<block:content>This is a default text</block:content>
</div>
<div id="sidebar">
<widget:advertisement type="wide" />
<block:sidebar this_param="is_passed_on" />
</div>
</body>
As you can see I made 2 sort of "extra" tags that will be replaced when eventually publishing the template. I load this layout like this:
$this->template->load("layout");
I then can manipulate the block tags like this:
$this->template->content = "I'm overwriting the default text";
$this->template->content->prepend("I forgot something");
$this->template->sidebar->view("viewfile_1", array(/*data*/));
$this->template->sidebar->view("viewfile_2", array(/*data*/));
I can set text manually, I can load multiple views into 1 block, I can use a few dom-like manipulating functions like prepend, append, ...
I can even extend the template with more layout options like:
$this->template->content->extend("2columns");
This layout file might look like:
<div><block:left/></div>
<div><block:right/></div>
So that instead of the content block I now have an extra left and right block to put content in.
I have also created a widget tag that loads the specific widget class (/widgets/advertisement in this case). The optional parameters added in the tags are passed on to the views files and/or widget display function together with the direct passed data array.
In short, this is how my system now works. I haven't really found other systems like this to get inspiration from. Could you guys give me advice on anything so I can put together one decent system that I can keep using?
My approach is:
Create main layouts for each page type on a layouts/ folder (think Wordpress layouts for home, archive, single post, single page)
Create common bits of interface in a common/ folder (think header, footer, sidebar, widget_XX, widget_YY)
Use Phil Sturgeon's Template Library (or Spark!) to handle the views.
On each controller I load all the data needed for rendering in $this->data and I pass that object to the view
Hope this helps! Good luck.

Beginner's guide to making a template driven PHP site

Do you know of any site that can help me start with making template driven sites in PHP?
First off I'll go ahead and start out with Smarty, since I've used it quite a lot. Since this is a community wiki, feel free to plug in examples of your own templating engine should you choose.
Installing Smarty
Templating provides a great way of structuring your HTML and separating out your HTML content from your logic code. It also provides a way to organize individual components of your HTML page, so it's easier to manage, and is more re-usable.
To start, we'll take at showing a simple page with Smarty. First off you need to actually get Smarty. So we'll head down to the Smarty download page. As of this writing, the latest stable version is Smarty 3.0.7, so we'll go ahead and download that. Downloading the .tar.gz file or the .zip file is up to the system you have. For Windows and Mac users (most likely using MAMP or XAMPP), .zip is probably a good choice, though you can always get programs to handle .tar.gz files. Users with Linux or *BSD type systems can grab the .tar.gz version.
Now then, we extract the file and get the following directory layout:
COPYING.lib
demo/
libs/
|__ Smarty.class.php
|__ ... some other files and folders ...
README
SMARTY2_BC_NOTES
Now, Smarty.class.php is the main file we're going to include to use Smarty. It's located in the libs directory. As 'libs' is a pretty generic sounding name, we're going to copy this to our document root folder, and rename it to Smarty. Now our theoretical document root folder is currently empty, so it will end up looking like this:
Smarty/
|__ Smarty.class.php
|__ ... some other files and folders ...
A Simple Template
Now that Smarty is installed, we'll create a very basic template and php script to show how it works. First off, to keep things organized we'll make a templates folder to keep our templates in. Then we'll create a mypage.php file, and a mypage.tpl file in our templates folder:
mypage.php
templates/
|__ mypage.tpl
Smarty/
|__ Smarty.class.php
|__ ... some other files and folders ...
mypage.php
<?php
require_once('Smarty/Smarty.class.php');
$smarty = new Smarty();
$smarty->assign("MYVAR", "Hello World");
$smarty->display("templates/mypage.tpl");
?>
templates/mypage.tpl
<html>
<head>
<title>My Sample Page</title>
</head>
<body>
<h1>{$MYVAR}</h1>
</body>
</html>
Now if we navigate to mypage.php, for example http://localhost:8000/mypage.php, "Hello World" will be displayed in large bold text. So what happend? Let's step through the code:
require_once('Smarty/Smarty.class.php');
Here we include the main Smarty class. We need this for any and all Smarty functionality.
$smarty->assign("MYVAR", "Hello World");
You'll be using this a lot. The assign command takes a value, "Hello World" in this example, and assigns it to a name, "MYVAR". If you look at the template:
<h1>{$MYVAR}</h1>
You'll notice {$MYVAR}. The {}'s indicate to Smarty that it needs to evaluate the expression inside. This could be a command or simply a variable. It could produce output or simply set a variable value. In this case, it simply outputs the value of $MYVAR that we assigned.
$smarty->display("templates/mypage.tpl");
Finally, we tell Smarty to parse the template, then display it as if you had simply echo'ed out HTML in a PHP page. Fancy eh? Now, a lot of people will want to iterate through arrays (ie. a set of db results), so let's take a look at an example of how to achieve that.
Looping Through Arrays
First we'll make adjustments to our code. The new listings are as follows:
mypage.php
<?php
require_once('Smarty/Smarty.class.php');
$myarray = array(
"John",
"Jane",
"Henry",
"Nancy",
"Gorilla"
);
$smarty = new Smarty();
$smarty->assign("MYARRAY", $myarray);
$smarty->display("templates/mypage.tpl");
?>
templates/mypage.tpl
<html>
<head>
<title>My Sample Page</title>
</head>
<body>
<h1>Results</h1>
<ul>
{foreach $MYARRAY as $myvalue}
<li>{$myvalue}</li>
{/foreach}
</ul>
</body>
</html>
If you reload the page, you'll get something like this:
Now, there are only a few changes to note:
$smarty->assign("MYARRAY", $myarray);
Instead of a string value, we assigned a variable which holds an array. This was passed to Smarty which used the data in the {foreach} loop:
<ul>
{foreach $MYARRAY as $myvalue}
<li>{$myvalue}</li>
{/foreach}
</ul>
The foreach in Smarty is much like the foreach of PHP. In this case, Smarty takes the array that was assigned to $MYVALUE and loops through it, setting $myvalue to the result of the current loop value. From there we can use {$myvalue} to refer to each individual item. Now, let's say we want to make this unordered list a widget to reuse in other places. We can do that through using templates themselves as variables.
Template Modularization
HTML can get very long very quickly. Smarty helps manage this by letting you break out parts of the page into individual components. So what we'll do is take our unordered list and put it into a separate page. Our new code will look like this:
mypage.php
<?php
require_once('Smarty/Smarty.class.php');
$myarray = array(
"John",
"Jane",
"Henry",
"Nancy",
"Gorilla"
);
$smarty = new Smarty();
$smarty->assign("MYARRAY", $myarray);
$content = $smarty->fetch("templates/mycontent.tpl");
$smarty->assign("MYCONTENT", $content);
$smarty->display("templates/mypage.tpl");
?>
templates/mypage.tpl
<html>
<head>
<title>My Sample Page</title>
</head>
<body>
<h1>Results</h1>
{$MYCONTENT}
</body>
</html>
mycontent.tpl
<ul>
{foreach $MYARRAY as $myvalue}
<li>{$myvalue}</li>
{/foreach}
</ul>
The result we get is the same, however the backend is now more organized. We can now reuse this mycontent.tpl file in other pages if we want. Common usages of this organization is making header, footer, and other parts of the page individual templates. This lets you narrow down to relevant pieces.
So what happened on the backend? The important command to take note of here is:
$content = $smarty->fetch("templates/mycontent.tpl");
fetch() works like display, except that instead of outputting it right away, it returns the result as a string of the rendered HTML. Note that because $MYARRAY is used in the mycontent.tpl, we have to assign the array right before it, not right before the final display() call. This ordering is important!
Conclusion
This concludes the very basic introduction to Smarty, and using a templating engine to work with managing your content. The Smarty Documentation provides a great resource for seeing all that smarty is capable of. Be sure to look through all the available commands to make sure you're using it efficiently!
Smarty for PHP is an adequate templating system. You can try and use that, plus their documentation to help develop a template driven website.
Depending on your needs you can create your own templateing system with a couple of included files.
Symfony, in addition to being a good framework, offers Twig.

How to include static html in php/smarty

I have been asked to include some html snippet in this php/smarty page. It's basically a sales agreement at the end of an overview page before you pay.
What is the code to include static html into my php/smarty template?
Thanks...
Do you mean include a file containing static HTML?
{include file="htmlfile.html"}
edit
As the file is just HTML, it might be better to use {fetch}, e.g.
{fetch file="path/to/html/file.html"}
For local files, either a full system
file path must be given, or a path
relative to the executed php script.
Like any other templates, smarty files are HTML files itself. you can just paste your HTML into smarty template.
If you are trying to include some code containing javascript or similar, you can use
{literal}{/literal} tags
to inlude a file you can use {include file="htmlfile.html"} as Tom said.
Before you display the template, in the PHP file try this:
$smarty->assign('Sectionfile','section-name.html');
$smarty->display('template.tpl');
in the template itself:
{include file="html_dir/$Sectionfile"}

Categories