I've just been passed an application to work on written in smarty templates so I'm unfamiliar with how the whole thing works.
So my problem is smarty is fetching a template from a file at application level so it affects every page on the site. I need a way of telling a single template to ignore the application level fetch.
So at application level it is echo $smarty->fetch('layout/main.html.tpl'); I just want to ignore that on one template. Can anyone help?
You'd want to add some logic to whatever point in the application is fetching that template. The issue isn't smarty, it's the application. A smarty template has no way of interfering with the php that renders it, nor can it introduce logic within the php script.
You would call $smarty->fetch() from a script, not a template. You can use logic to choose a different template name and fetch whatever template is appropriate, so a single script can easily call any of your templates.
For instance...
$template = 'error.tpl';
if($conditions =='right')
{
$template = 'normal.tpl';
}
echo $smarty->fetch("layout/$template");
Also, note that you can use the display() method rather than echo with fetch():
$smarty->display("layout/$template");
This way you're not storing the template into a variable you're just going to output.
If it's a simple case where one script calls template "A" and another calls template "B"...
//call in template A
$smarty->display("layout/templateA.tpl");
//call in template B
$smarty->display("layout/templateB.tpl");
No need for extra logic in that case.
Related
in smarty Smarty_Compiler.class.php performed some operation between two tags like {if}{/if}
if i want to get text within the new tag then how to proceedi tried inside
function _compile_tag($template_tag)
{
....
switch ($tag_command) {
-----
case 'newtag':
break;
case '/newtag':
break;
}
How can i get the content of tpl within the new tag
You should create a Smarty plugin. You can read documentations here (about extending Smarty) and here (more specific, about create block functions plugins).
Basically, you have to create your smarty_make_pdf() PHP function (see parameters in the second link I gave you), place it in a file called block.make_pdf.php (see here) and tell Smarty to search for plugins in the folder you created that file using $smarty->addPluginsDir() (see here).
PS: I'm supposing you are using Smarty 3.
You really shouldn't be editing the core Smarty code to achieve this.
Look into registerPlugin() if you're using Smarty 3 (or register_block() if you're on Smarty 2).
These methods will allow you to create your own Smarty tags and write handler functions that implement them.
I am currently implementing the navigation of the website (multilevel menu, having current page highlighted).
As navigation part will be included for virtually all modules, I first made it a global partial.
But logic for selection of "current page" is quite complicated in some situations, I am thinking of using a component for the navigation.
The problem is that symfony allows to have global partials, but not global components.
So is there a "nice symfony way" to do this?
There isn't a mechanism for this as such. I usually end up creating an empty module called default and putting stuff like that in there.
What's wrong with:
<?php include_component('someModule', 'navigationComponent') ?>
... where you store it in some general module (e.g. "general") and call it wherever you want, including your layouts. Isn't that global enough?
This is your solution:
Create the yourproject/yourapp/templates/_globalpartial.php with this content:
<?php include_component('yourmodule', 'yourcomponent'); ?>
And use this globalpartial.php in yourproject/yourapp/templates/layout.php
I'm using the term "partial" to refer to a small section of presentational code which is repeated on many views. For example, a sidebar. In vanilla PHP, where the business and presentation logic is mixed, including a sidebar is no trouble:
if($someCondition) {
include('sidebar.php');
}
However, in an MVC design pattern, the presentational logic must be kept in the view whilst the business logic must be kept in the controller. If I wish to include a partial unconditionally, then this is unproblematic since I can just have include('sidebar.php') in my view. However, I can no longer do so conditionally because that if logic is banned from my view.
I have attempted a number of solutions but they all have problems. I am currently using Solution 2:
Solution 1
Create an include function in my view class which could conditionally include content from my controller. So in my controller I could have the following logic:
if($someCondition) {
$this->view->include('sidebar.php');
}
$this->view->show('index.php');
Problems: sidebar.php will need to be included into index.php at a specific point requiring the include method on the view object to do some sort of parsing.
Solution 2
Move control of the partials out of the view and put them into the controller:
if($someCondition) {
$this->view->show('header.php', 'sidebar.php', 'index.php', 'footer.php');
}
else {
$this->view->show('header.php', 'index.php', 'footer.php');
}
Problems: Moves a large portion of the presentational logic into the realm of the controller. It seems to be more natural to me for the view to decide whether or not to include the header. Indeed, every PHP MVC tutorial I can find, has partials under the control of the view and not the controller.
Solution 3
Duplicate the view and alter the clone so that it includes the sidebar. Then I could conditionally load one or the other in the controller:
if($someCondition) {
$this->view->show('indexWithSidebar.php');
}
else {
$this->view->show('index.php');
}
Problems: Duplication of code. Consider what would happen if I had 2 sidebars which I needed to be conditionally loaded. Then I would need index.php, indexWithSidebar1.php, indexWithSidebar2.php, indexWithSidebar1And2.php. This only gets worse with every condition. Remember that the entire point of taking the sidebar out as a partial was to avoid replicating it anyway and this approach seems to defeat the point.
Are any of these solutions the "right" solution and if so, how can I overcome their problems? Is there a better approach out there?
However, in an MVC design pattern, the
presentational logic must be kept in
the view whilst the business logic
must be kept in the controller.
IMHO: From an architecture standpoint, I push my business logic further back, out of the controller. We use services to handle all the business logic and repositories for data retrieval. The services call the repositories and then pass back our data model with all the business logic decided for us. Any logic outside that is really UI logic (show this, hide that), as our returned data could be (should be able to be) used in any kind of application, whether it's a mobile app, windows app, or web app.
You could use an extension helper method for your control, and in the model for the partial you can return EmptyResult() if you don't wish to render the sidebar. Or, more succintly:
<% Html.RenderAction<MyController>(x => x.Sidebar({params})); %>
And then in the controller:
public ViewResult Sidebar({params})
{
SidebarModel model = new SidebarModel();
//...get/build model
if ({someCondition})
{
return View("MySidebarPartialView", model);
}
return new EmptyResult();
}
Have your controller evaluate the condition and pass the result to your view. Then, the view can decide whether to include the partial.
For example, the controller can check whether a variable, $foo, isn't null. It passes the result of the comparison to the view via the model's property, $model->isFooed. In this case, the view can display the sidebar based on the value of $model->isFooed.
The Smarty FAQ suggests one way to handle cacheable fragments, but it needs each page controller to do tons of work up-front, instead of encapsulating things properly.
We want to get to a stage where we can do something like:
<div id="header">
{our_categories}
{our_subcategories category=$current_category}
</div>
The output of the our_ prefixed functions should be completely cacheable, only relying on the named parameters (if any.) If we referred to {our_categories} in more than one template, they should all refer to the same cached content.
(it's probably worth mentioning that we tried using {insert name="..."} and coding up our own functions, but the results weren't cacheable, and we ended up hand-cranking the HTML retunred, rather than benefiting from Smarty's template processing.)
Our first crack at this uses a custom function smarty_function_our_categories, but the caching's going horribly wrong. Here's what our function looks like:
function smarty_function_our_categories($params, &$smarty) {
$smarty->caching = 2;
$smarty->cache_lifetime = 3600; # 1 hour
if (!$smarty->is_cached(...)) {
// ... do db access to fetch data for template...
$smarty->assign(....);
}
return $smarty->fetch(...);
}
The problem is: calling $smarty->fetch() within a function confuses smarty, making it lose track of which templates have insert-tags, and which don't. The end result is that Smarty forgets to replace certain markers when serving up cached content (markers it puts there to say: "replace this with the results of some non-caching {insert ...} call.) In our case, this manifests itself with our site showing a couple of md5 checksums and a php-serialized memento where our main menu should be - that's not good.
We assume we've made a mistake in how we're building our components, so the question finally becomes:
How do you safely create a caching component using Smarty to render itself?
You should not change caching parameters from inside Smarty function. Wheither or not the result of the plugin output is cacheable is defined when you register plugin.
http://www.smarty.net/manual/en/caching.cacheable.php
To create uncachable content inside cachable template just use {dynamic} blocks like this:
//Registering dynamic non-caching block with Smarty
$template->register_block('dynamic', 'smarty_block_dynamic', false);
function smarty_block_dynamic($param, $content, &$smarty) {
return $content;
}
I'm using CodeIgniter, and will likely use their template library as I want to keep things extremely simple to use. The content for the template variables will come from the database, but I want the business admins to know what content areas are available. Basically the names of the parameters when they choose a specific template. For instance, Joomla uses an extra XML file that defines each area, whereas Wordpress uses comments within a page template to inform the system that the PHP file is a template. I like the Joomla approach because you don't have to parse the PHP file to find the areas, but I like the Wordpress approach because you don't have an extra XML file associated with every template. Are there other approaches that I'm missing?
I think the nicest way would be to add a small hack to the template parser class. The code looks quite readable and clean in system/libraries/Parser.php. You could insert a hook in that class that can be used to keep track of the variables. I don't know, if it works, but here's a snippet:
class CI_Parser {
var $varCallback;
function setVarCallback($callbackFunction) {
$this->varCallback = $callbackFunction;
}
...
function _parse_single(...) {
$callback = $this->varCallback;
$callback($key);
}
...
//Somewhere in your code
function storeVarName($variableName) {
// Persist the variable name wherever you want here
}
$this->parser->setVarCallback('storeVarName');
You could do this directly in the controller:
// in the controller
print_r($data);
$this->load->view("main", $data);
Or a little more rudimentary, but you could pass to the template a PHP array of variables (or an object):
// in the controller
$data = array();
$data["namespace"] = array(
"title" => "My website",
"posts" => array("hi", "something else")
);
$this->load->view("main", $data);
And then in the view, have a flag to print_r the namespace to show all the vars available, so that business admins know exactly what to use.
// in the view
if(isset($namespace["showAllVars"])) print_r($namespace);
One option would be to call token_get_all on the PHP file (only when your business admins are loading it up), and parse the output of that.
The best approach, in my opinion, is to keep the variable definitions in another place (such as a database table, or a separate file). This will help with testing (i.e., a programmer can't just remove a tag and it's gone) and making sure things are still working as you move on with the application development in time.
Another advantage is that your application logic will be independent from the templating engine.
On a side note, if you expect a lot of traffic, you may consider using smarty instead. We have done extensive testing with most of the templating engines around and smarty is the fastest.