SmartyBundle

Note

A Symfony2 bundle that provides integration for the Smarty3 template engine.

_images/symfony-50.png _images/smarty-50.png

Introduction

This bundle was created to support Smarty in Symfony2, providing an alternative to the Twig template engine natively supported.

Note

An effort was made to provide, where possible, the same user configuration and extensions available for the Twig bundle. This is to allow easy switching between the two bundles (at least I hope so!).

What is Smarty?

Smarty is a template engine for PHP, facilitating the separation of presentation (HTML/CSS) from application logic. This implies that PHP code is application logic, and is separated from the presentation.

Some of Smarty’s features: [1]

  • It is extremely fast.
  • It is efficient since the PHP parser does the dirty work.
  • No template parsing overhead, only compiles once.
  • It is smart about recompiling only the template files that have changed.
  • You can easily create your own custom functions and variable modifiers, so the template language is extremely extensible.
  • Configurable template {delimiter} tag syntax, so you can use {$foo}, {{$foo}}, <!--{$foo}-->, etc.
  • The {if}..{elseif}..{else}..{/if} constructs are passed to the PHP parser, so the {if...} expression syntax can be as simple or as complex an evaluation as you like.
  • Allows unlimited nesting of sections, if’s etc.
  • Built-in caching support.
  • Arbitrary template sources.
  • Template Inheritance for easy management of template content.
  • Plugin architecture.

See the Smarty3 Manual for other features and information on it’s syntax, configuration and installation.

[1]http://www.smarty.net/docs/en/what.is.smarty.tpl

Requirements

License

This bundle is licensed under the LGPL-3 License. See the LICENSE file for details.

Installation

Download SmartyBundle

Tell composer to add the bundle to your composer.json by running the command:

$ php composer.phar require noiselabs/smarty-bundle ~2.0

Composer will install the bundle to your project’s vendor/noiselabs directory.

Enable the bundle

Enable the bundle in the kernel:

// app/AppKernel.php

public function registerBundles()
{
    $bundles = array(
        // ...
        new NoiseLabs\Bundle\SmartyBundle\SmartyBundle(),
    );
}

Enable the Smarty template engine in the config

# app/config/config.yml
# ...
framework:
    templating:
        engines: ['twig', 'php', 'smarty']

Warning

You need to enable the php engine as well. Otherwise some services will not work as expected. See `https://github.com/symfony/symfony/issues/14719`_

Usage

Basic usage

You can render a Smarty template instead of a Twig one simply by using the .smarty extension in the template name instead of .twig. The controller below renders the index.html.smarty template:

// src/AppBundle/Controller/DefaultController.php

public function indexAction(Request $request)
{
    return $this->render('default/index.html.smarty');
}

Template Inheritance

Like Symfony2 PHP renderer or Twig, Smarty provides template inheritance.

Note

Template inheritance is an approach to managing templates that resembles object-oriented programming techniques. Instead of the traditional use of {include ...} tags to manage parts of templates, you can inherit the contents of one template to another (like extending a class) and change blocks of content therein (like overriding methods of a class.) This keeps template management minimal and efficient, since each template only contains the differences from the template it extends.

Let’s assume you have a app/Resources/views/base.html.smarty as layout

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8" />
    <title>{block name=title}Welcome!{/block}</title>
    {block name=stylesheets}{/block}
</head>
<body>
{block name=body}{/block}
{block name=javascripts}{/block}
</body>
</html>

and app/Resources/views/default/index.html.smarty for the content

{extends 'file:base.html.smarty'}
{block name=title}Welcome to the SmartyBundle{/block}
{block name=body}Welcome to the SmartyBundle{/block}

Then the output of index.html.smarty will be:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8" />
    <title>Welcome to the SmartyBundle</title>
</head>
<body>
Welcome to the SmartyBundle
</body>
</html>

Referencing Templates

There are several possibilites to reference templates:

  1. file:base.html.smarty: To load a template that lives in the app/Resources/views directory of the project you should use the following syntax:

    {extends 'file:base.html.smarty'}
    
  2. file:AppBundle::index.html.smarty: This syntax is the same as with twig.

    {extends 'file:AppBundle::base.html.smarty'}
    
  3. file:[AppBundle]/base.html.smarty: Instead of the colon (:) separated syntax you can use smarty native syntax which should be, performance wise, slightly better/faster. But it works only within templates (not in the Controller), so for consistency’s sake you might want to prefer the colon separated syntax one.

    {extends 'file:[AppBundle]/base.html.smarty'}
    

Please see Symfony2 - Template Naming and Locations to learn more about the naming scheme and template locations supported in Symfony2.

{include} functions work the same way as the examples above.:

{include 'file:AppBundle::base.html.smarty'}
{include 'file:[AppBundle]/base.html.smarty'}
{include 'file:base.html.smarty'}

Warning

Note the usage of the file: resource in the {extends} function. We need to declare the resource even if the Smarty class variable $default_resource_type is set to 'file'. This is required because we need to trigger a function to handle ‘logical’ file names (only mandatory if you are using the first syntax). Learn more about resources in the Smarty Resources webpage.

Note

The .html.smarty extension can simply be replaced by .smarty. We are prefixing with .html to stick with the Symfony convention of defining the format (.html) and engine (.smarty) for each template.

Cookbook

Injecting variables into all templates (i.e. Global Variables)

As exemplified in the Symfony Cookbook it is possible to make a variable to be accessible to all the templates you use by configuring your app/config/config.yml file:

# app/config/config.yml
smarty:
    # ...
    globals:
        ga_tracking: UA-xxxxx-x

Now, the variable ga_tracking is available in all Smarty templates:

<p>Our google tracking code is: {$ga_tracking} </p>

Trim unnecessary whitespace from HTML markup

This technique can speed up your website by eliminating extra whitespace characters and thus reducing page size. It removes HTML comments (except ConditionalComments) and reduces multiple whitespace to a single space everywhere but <script>, <pre>, <textarea> [1].

To enable this feature add the trimwhitespace output filter in app/config/config.yml:

# app/config/config.yml

# Smarty configuration
smarty:
    options:
        autoload_filters:
            output: [trimwhitespace]
[1]http://stackoverflow.com/a/9207456/545442

Commands

SmartyBundle extends the default Symfony2 command line interface by providing the commands described below.

Compile Command

smarty:compile

Compiles all known Smarty templates.

Usage

The following command finds all known Smarty templates and compiles them:

php app/console smarty:compile

Alternatively you may pass an optional @AcmeMyBundle argument to only search for templates in a specific bundle:

php app/console smarty:compile @AcmeMyBundle

Available Options

  • --force - Force the compilation of all templates even if they weren’t modified.
  • --verbose - Print information about each template being currently compiled.

Extensions

SmartyBundle extensions are packages that add new features to Smarty. The extension architecture implemented in the SmartyBundle is an object-oriented approach to the plugin system available in Smarty. The implemented architecture was inspired by Twig Extensions.

Each extension object share a common interest (translation, routing, etc.) and provide methods that will be registered as a Smarty plugin before rendering a template. To learn about the plugin ecosystem in Smarty take a look at the Smarty documentation page on that subject.

The SmartyBundle comes with a few extensions to help you right away. These are described in the next section.

Actions Extension

This extension tries to provide the same funcionality described in Symfony - Templating - Embedding Controllers.

Following the example presented in the link above, the Smarty equivalents are:

Using a block function:

{render attributes=['min'=>1,'max'=>3]}AcmeArticleBundle:Article:recentArticles{/render}

Using a modifier:

{'AcmeArticleBundle:Article:recentArticles'|render:['min'=>1,'max'=>3]}

Assetic Extension

See chapter Assetic for complete documentation about Assetic support in SmartyBundle.

Assets Extension

Templates commonly refer to images, JavaScript, stylesheets and other assets. You could hard-code the path to these assets (e.g. /images/logo.png), but SmartyBundle provides a more dynamic option via the asset modifier:

<img src="{'images/logo.png'|asset}" />

or asset block:

<link href="{asset}css/blog.css{/asset}" rel="stylesheet" type="text/css" />

This bundle also provides the assets_version function to return the version of the assets in a package. To set the version see the assets_version configuration option in Symfony’s Framework Bundle.

Usage in template context:

{assets_version}

Form Extension

Form extension provides support for Symfony Forms and it is described in its own chapter. Go there now.

Routing Extension

To generate URLs from a Smarty template you may use two block functions (path and url) provided by the RoutingExtension.

path block:

<a href="{path slug='my-blog-post'}blog_show{/path}">
    Read this blog post.
</a>

path modifier:

<a href="{'blog_show|path:['slug' => 'my-blog-post']}">
    Read this blog post.
</a>

Absolute URLs can also be generated.

url block:

<a href="{url slug='my-blog-post'}blog_show{/url}">
    Read this blog post.
</a>

url modifier:

<a href="{'blog_show'|url ['slug' => 'my-blog-post']}">
    Read this blog post.
</a>

Please see the Symfony - Routing for full information about routing features and options in Symfony.

Translation Extension

To help with message translation of static blocks of text in template context, the SmartyBundle, provides a translation extension. This extension is implemented in the class TranslationExtension.

You may translate a message, in a template, using a block or modifier. Both methods support the following arguments:

count
In pluralization context, used to determine which translation to use and also to populate the %count% placeholder (only available in transchoice);
vars
Message placeholders;
domain
Message domain, an optional way to organize messages into groups;
locale
The locale that the translations are for (e.g. en_GB, en, etc);

trans block:

{trans}Hello World!{/trans}

{trans vars=['%name%' => 'World']}Hello %name%{/trans}

{trans domain="messages" locale="pt_PT"}Hello World!{/trans}

<!-- In case you're curious, the latter returns "Olá Mundo!" :) -->

trans modifier:

{"Hello World!"|trans}

{"Hello %name%"|trans:['%name%' => 'World']}

{"Hello World!"|trans:[]:"messages":"pt_PT"}

Message pluralization can be achieved using transchoice:

Warning

Unlike the examples given in the Symfony documentation, which uses curly brackets for explicit interval pluralization we are using square brackets due to Smarty usage of curly brackets as syntax delimiters. So {0} There is no apples becomes [0] There is no apples.

transchoice block:

{transchoice count=$count}[0] There is no apples|[1] There is one apple|]1,Inf] There is %count% apples{/transchoice}

transchoice modifier:

{'[0] There is no apples|[1] There is one apple|]1,Inf] There is %count% apples'|transchoice:$count}
<!-- Should write: "There is 5 apples" -->

The transchoice block/modifier automatically gets the %count% variable from the current context and passes it to the translator. This mechanism only works when you use a placeholder following the %var% pattern.

Security Extension

This extension provides access control inside a Smarty template. This part of the security process is called authorization, and it means that the system is checking to see if you have privileges to perform a certain action. For full details about the Symfony security system check it’s documentation page.

If you want to check if the current user has a role inside a template, use the built-in is_granted modifier.

Usage:

{if 'IS_AUTHENTICATED_FULLY'|is_granted:$object:$field}
    <a href="...">Delete</a>
{else}
    <!-- no delete for you -->
{/if}

Note

If you use this function and are not at a URL behind a firewall active, an exception will be thrown. Again, it’s almost always a good idea to have a main firewall that covers all URLs.

Complex Access Controls with Expressions

Note

The expression functionality was introduced in Symfony 2.4.

In addition to a role like ROLE_ADMIN, the isGranted method also accepts an Expression object.

You can use expressions inside your templates like this:

{if '"ROLE_ADMIN" in roles or (user and user.isSuperAdmin())'|expression|is_granted}
    <a href="...">Delete</a>
{/if}

In this example, if the current user has ROLE_ADMIN or if the current user object’s isSuperAdmin() method returns true, then access will be granted (note: your User object may not have an isSuperAdmin method, that method is invented for this example).

For more details on expressions and security, see the section Complex Access Controls with Expressions in the Symfony book.

Using CSRF Protection in the Login Form

The security extension also adds a modifer to support CSRF Protection in login forms. Please read Using CSRF Protection in the Login Form from the Symfony Documentation for general CSRF Protection setup. The template for rendering should look like this:

<input type="hidden" name="_csrf_token" value="{'authenticate'|csrf_token}">

Enabling custom Extensions

To enable a Smarty extension, add it as a regular service in one of your configuration, and tag it with smarty.extension. The creation of the extension itself is described in the next section.

  • YAML
    services:
        smarty.extension.your_extension_name:
            class: Fully\Qualified\Extension\Class\Name
            arguments: [@service]
            tags:
                - { name: smarty.extension }
    

Creating a SmartyBundle Extension

Note

In version 0.1.0 class AbstractExtension was simply named Extension. Please update your code when migrating to 0.2.0.

An extension is a class that implements the ExtensionInterface. To make your life easier an abstract AbstractExtension class is provided, so you can inherit from it instead of implementing the interface. That way, you just need to implement the getName() method as the Extension class provides empty implementations for all other methods.

The getName() method must return a unique identifier for your extension:

namespace NoiseLabs\Bundle\SmartyBundle\Extension;

class TranslationExtension extends AbstractExtension
{
    public function getName()
    {
        return 'translator';
    }
}

Plugins

Plugins can be registered in an extension via the getPlugins() method. Each element in the array returned by getPlugins() must implement PluginInterface.

For each Plugin object three parameters are required. The plugin name comes in the first parameter and should be unique for each plugin type. Second parameter is an object of type ExtensionInterface and third parameter is the name of the method in the extension object used to perform the plugin action.

Please check available method parameters and plugin types in the Extending Smarty With Plugins webpage.

namespace NoiseLabs\Bundle\SmartyBundle\Extension;

use NoiseLabs\Bundle\SmartyBundle\Extension\Plugin\BlockPlugin;

class TranslationExtension extends Extension
{
    public function getPlugins()
    {
        return array(
            new BlockPlugin('trans', $this, 'blockTrans'),
        );
    }

    public function blockTrans(array $params = array(), $message = null, $template, &$repeat)
    {
        $params = array_merge(array(
            'arguments' => array(),
            'domain'    => 'messages',
            'locale'    => null,
        ), $params);

        return $this->translator->trans($message, $params['arguments'], $params['domain'], $params['locale']);
    }
}

Filters

Filters can be registered in an extension via the getFilters() method.

Each element in the array returned by getFilters() must implement FilterInterface.

namespace NoiseLabs\Bundle\SmartyBundle\Extension;

use NoiseLabs\Bundle\SmartyBundle\Extension\Filter\PreFilter;

class BeautifyExtension extends Extension
{
    public function getFilters()
    {
        return array(
            new PreFilter($this, 'htmlTagsTolower'),
        );
    }

    // Convert html tags to be lowercase
    public function htmlTagsTolower($source, \Smarty_Internal_Template $template)
    {
        return preg_replace('!<(\w+)[^>]+>!e', 'strtolower("$1")', $source);
    }
}

Globals

Global variables can be registered in an extension via the getGlobals() method.

There are no restrictions about the type of the array elements returned by getGlobals().

namespace NoiseLabs\Bundle\SmartyBundle\Extension;

class GoogleExtension extends Extension
{
    public function getGlobals()
    {
        return array(
            'ga_tracking' => 'UA-xxxxx-x'
        );
    }
}

Assetic

Hint

Assetic is an asset management framework for PHP. This extensions provides support for it’s usage in Symfony2 when using Smarty templates.

Assetic combines two major ideas: assets and filters. The assets are files such as CSS, JavaScript and image files. The filters are things that can be applied to these files before they are served to the browser. This allows a separation between the asset files stored in the application and the files actually presented to the user.

Installation

See the Symfony Manual for Installation Instructions.

When installing symfony/assetic-bundle you need to enable the twig template engine. Otherwise you will get a ServiceNotFoundException.

# app/config/config.yml
# ...
framework:
    templating:
        engines: ['twig', 'smarty']

Also make sure you disable assetic controllers.

Usage

Using Assetic provides many advantages over directly serving the files. The files do not need to be stored where they are served from and can be drawn from various sources such as from within a bundle:

{javascripts
    assets='@AcmeFooBundle/Resources/public/js/*'
}
<script type="text/javascript" src="{$asset_url}"></script>
{/javascripts}

To bring in CSS stylesheets, you can use the same methodologies seen in this entry, except with the stylesheets tag:

{stylesheets
    assets='@AcmeFooBundle/Resources/public/css/*'
}
<link rel="stylesheet" href="{$asset_url}" />
{/stylesheets}

Combining Assets

You can also combine several files into one. This helps to reduce the number of HTTP requests, which is great for front end performance. It also allows you to maintain the files more easily by splitting them into manageable parts. This can help with re-usability as you can easily split project-specific files from those which can be used in other applications, but still serve them as a single file:

{javascripts
    assets='@AcmeFooBundle/Resources/public/js/*,
            @AcmeBarBundle/Resources/public/js/form.js,
            @AcmeBarBundle/Resources/public/js/calendar.js'
}
<script src="{$asset_url}"></script>
{/javascripts}

In the dev environment, each file is still served individually, so that you can debug problems more easily. However, in the prod environment, this will be rendered as a single script tag.

Block attributes

Here is a list of the possible attributes to define in the block function.

  • assets: A comma-separated list of files to include in the build (CSS, JS or image files)
  • debug: If set to true, the plugin will not combine your assets to allow easier debug
  • filter: A coma-separated list of filters to apply. Currently, only LESS and YuiCompressor (both CSS and JS) are supported
  • combine: Combine all of your CSS and JS files (overrides debug)
  • output: Defines the URLs that Assetic produces
  • var_name: The variable name that will be used to pass the asset URL to the <link> tag
  • as: An alias to var_name. Example: as='js_url'
  • vars: Array of asset variables. For a description of this recently added feature please check out the Johannes Schmitt blog post about Asset Variables in Assetic.

Warning

Unlike the examples given in the Asset Variables in Assetic, which uses curly brackets for the vars placeholder we are using square brackets due to Smarty usage of curly brackets as syntax delimiters. So js/messages.{locale}.js becomes js/messages.[locale].js.

Full example

Example using all available attributes:

{javascripts
    assets='@AcmeFooBundle/Resources/public/js/*,
            @AcmeBarBundle/Resources/public/js/form.js,
            @AcmeBarBundle/Resources/public/js/calendar.js',
            @AcmeBarBundle/Resources/public/js/messages.[locale].js
    filter='yui_js'
    output='js/compiled/main.js'
    var_name='js_url'
    vars=['locale']
}
<script src="{$js_url}"></script>
{/javascripts}

Symfony/Assetic documentation

For further details please refer to the Symfony documentation pages about Assetic:

Forms

Symfony integrates a Form component that makes dealing with forms easy. In this chapter, you’ll see how to render Symfony forms in Smarty templates. Oh yeah!

Warning

Form support in SmartyBundle is currently under development and it is expected to be broken here and there. Please be patient and don’t be shy to share your experiences with this extension. It will help us improve it. Thanks!

Rendering a Form

First you need to create a form instance as described in Creating a Simple Form.

// src/Acme/TaskBundle/Controller/DefaultController.php
namespace Acme\TaskBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Acme\TaskBundle\Entity\Task;
use Symfony\Component\HttpFoundation\Request;

class DefaultController extends Controller
{
    public function newAction(Request $request)
    {
        // create a task and give it some dummy data for this example
        $task = new Task();
        $task->setTask('Write a blog post');
        $task->setDueDate(new \DateTime('tomorrow'));

        $form = $this->createFormBuilder($task)
            ->add('task', 'text')
            ->add('dueDate', 'date')
            ->getForm();

        return $this->render('AcmeTaskBundle:Default:new.html.smarty', array(
            'form' => $form->createView(),
        ));
    }
}

Once you create a form instance, the next step is to render it. This is done by passing a special form “view” object to your template (notice the $form->createView() in the controller above) and using a set of form helper functions:

{* src/Acme/TaskBundle/Resources/views/Default/new.html.smarty *}
<form action="{'task_new'|path}" method="post" {form_enctype form=$form}>
    {form_widget form=$form}

    <input type="submit" />
</form>

More examples coming soon…

Twitter Bootstrap integration

Twitter Bootstrap is an extensive front-end toolkit for developing web sites and applications released by Twitter developers.

MopaBootstrapBundle is a Symfony2 Bundle that integrates Bootstrap into Symfony2 project.

SmartyBundle builds upon these tools to give you a quick way to start a project using Symfony2 + TwitterBootstrap + Smarty3. Enjoy!

Note

Examples presented here use only the most common/preferred tool for a given task. For complete reference please check MopaBootstrapBundle documentation.

Installation

Composer (Symfony 2.1.x)

Add the following packages and scripts to composer.json:

{
    "require": {
        "php": ">=5.3.8",

        "symfony/framework-standard-edition": "dev-master",

        "noiselabs/smarty-bundle": "dev-twitter-bootstrap",

        "mopa/bootstrap-bundle": "dev-master",
        "twitter/bootstrap": "master",
        "knplabs/knp-paginator-bundle": "dev-master",
        "knplabs/knp-menu-bundle": "dev-master",
        "craue/formflow-bundle": "dev-master",
        "thomas-mcdonald/bootstrap-sass": "dev-master",
        "mopa/bootstrap-sandbox-bundle": "dev-master",
        "liip/theme-bundle": "dev-master"
    },

    "scripts": {
        "post-install-cmd": [
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::buildBootstrap",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::clearCache",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installAssets",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installRequirementsFile",
            "Mopa\\Bundle\\BootstrapBundle\\Composer\\ScriptHandler::postInstallSymlinkTwitterBootstrap",
            "Mopa\\Bundle\\BootstrapBundle\\Composer\\ScriptHandler::postInstallSymlinkTwitterBootstrapSass"
        ],
        "post-update-cmd": [
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::buildBootstrap",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::clearCache",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installAssets",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installRequirementsFile",
            "Mopa\\Bundle\\BootstrapBundle\\Composer\\ScriptHandler::postInstallSymlinkTwitterBootstrap",
            "Mopa\\Bundle\\BootstrapBundle\\Composer\\ScriptHandler::postInstallSymlinkTwitterBootstrapSass"
        ]
    },

    "include-path": ["vendor/smarty/smarty/distribution/libs/"],

    "repositories": [
        {
            "type": "package",
            "package": {
                "version": "master",
                "name": "twitter/bootstrap",
                "source": {
                    "url": "https://github.com/twitter/bootstrap.git",
                    "type": "git",
                    "reference": "master"
                },
                "dist": {
                    "url": "https://github.com/twitter/bootstrap/zipball/master",
                    "type": "zip"
                }
            }
        },
        {
            "type":"package",
            "package": {
                "version":"dev-master",
                "name":"thomas-mcdonald/bootstrap-sass",
                "source": {
                    "url":"https://github.com/thomas-mcdonald/bootstrap-sass.git",
                    "type":"git",
                    "reference":"master"
                },
                "dist": {
                    "url":"https://github.com/thomas-mcdonald/bootstrap-sass/zipball/master",
                    "type":"zip"
                }
            }
        }
    ]
}

Now tell composer to update vendors by running the command:

$ php composer.phar update

Enable the bundles

// app/AppKernel.php

class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = array(
            // ...
            new NoiseLabs\Bundle\SmartyBundle\SmartyBundle(),

            new Mopa\Bundle\BootstrapBundle\MopaBootstrapBundle(),
            new Mopa\Bundle\BootstrapSandboxBundle\MopaBootstrapSandboxBundle()
            new Knp\Bundle\MenuBundle\KnpMenuBundle(),
            new Knp\Bundle\PaginatorBundle\KnpPaginatorBundle(),
            new Liip\ThemeBundle\LiipThemeBundle()
        );

        // ...

        return $bundles;
    }
}

Enable the Smarty template engine

  • YAML
    # app/config/config.yml
    
    framework:
        templating:      { engines: ['twig', 'smarty'] }
    

Configuration

  • YAML
    # app/config/config.yml
    
    # MopaBootstrap Configuration
    #
    mopa_bootstrap:
        # To load the navbar extensions (template helper, CompilerPass, etc.)
        navbar: ~
    

Configuration Reference

The example below uses YAML format. Please adapt the example if using XML or PHP.

app/config/config.yml:

smarty:

    options:

        # See http://www.smarty.net/docs/en/api.variables.tpl
        allow_php_templates:
        allow_php_templates:
        auto_literal:
        autoload_filters:
        cache_dir:                           %kernel.cache_dir%/smarty/cache
        cache_id:
        cache_lifetime:
        cache_locking:
        cache_modified_check:
        caching:
        caching_type:
        compile_check:
        compile_dir:                         %kernel.cache_dir%/smarty/templates_c
        compile_id:
        compile_locking:
        compiler_class:
        config_booleanize:
        config_dir:                          %kernel.root_dir%/config/smarty
        config_overwrite:
        config_read_hidden:
        debug_tpl:
        debugging:
        debugging_ctrl:
        default_config_type:
        default_modifiers:
        default_resource_type:               file
        default_config_handler_func:
        default_template_handler_func:
        direct_access_security:
        error_reporting:
        escape_html:
        force_cache:
        force_compile:
        inheritance_merge_compiled_includes: true
        left_delimiter:
        locking_timeout:
        merge_compiled_includes:
        php_handling:
        plugins_dir:                         []
        right_delimiter:
        smarty_debug_id:
        template_dir:                        %kernel.root_dir%/Resources/views
        trim_whitespace :                    false
        trusted_dir:
        use_include_path:                    false
        use_sub_dirs:                        true

    globals:

        # Examples:
        foo:                 "@bar"
        pi:                  3.14

Available options

allow_php_templates
By default the PHP template file resource is disabled. Setting $allow_php_templates to TRUE will enable PHP template files.
auto_literal
The Smarty delimiter tags { and } will be ignored so long as they are surrounded by white space. This behavior can be disabled by setting auto_literal to false.
autoload_filters
If there are some filters that you wish to load on every template invocation, you can specify them using this variable and Smarty will automatically load them for you. The variable is an associative array where keys are filter types and values are arrays of the filter names.
cache_dir
This is the name of the directory where template caches are stored. By default this is %kernel.cache_dir%/smarty/cache. This directory must be writeable by the web server.
cache_id
Persistent cache_id identifier. As an alternative to passing the same $cache_id to each and every function call, you can set this $cache_id and it will be used implicitly thereafter. With a $cache_id you can have multiple cache files for a single call to display() or fetch() depending for example from different content of the same template.
cache_lifetime
This is the length of time in seconds that a template cache is valid. Once this time has expired, the cache will be regenerated. See the page Smarty Class Variables - $cache_lifetime for more details.
cache_locking
Cache locking avoids concurrent cache generation. This means resource intensive pages can be generated only once, even if they’ve been requested multiple times in the same moment. Cache locking is disabled by default.
cache_modified_check
If set to TRUE, Smarty will respect the If-Modified-Since header sent from the client. If the cached file timestamp has not changed since the last visit, then a ‘304: Not Modified’ header will be sent instead of the content. This works only on cached content without {insert} tags.
caching
This tells Smarty whether or not to cache the output of the templates to the $cache_dir. By default this is set to the constant Smarty::CACHING_OFF. If your templates consistently generate the same content, it is advisable to turn on $caching, as this may result in significant performance gains.
caching_type
This property specifies the name of the caching handler to use. It defaults to file, enabling the internal filesystem based cache handler.
compile_check
Upon each invocation of the PHP application, Smarty tests to see if the current template has changed (different timestamp) since the last time it was compiled. If it has changed, it recompiles that template. If the template has yet not been compiled at all, it will compile regardless of this setting. By default this variable is set to TRUE. Once an application is put into production (ie the templates won’t be changing), the compile check step is no longer needed. Be sure to set $compile_check to FALSE for maximum performance. Note that if you change this to FALSE and a template file is changed, you will not see the change since the template will not get recompiled. If $caching is enabled and $compile_check is enabled, then the cache files will get regenerated if an involved template file or config file was updated. As of Smarty 3.1 $compile_check can be set to the value Smarty::COMPILECHECK_CACHEMISS. This enables Smarty to revalidate the compiled template, once a cache file is regenerated. So if there was a cached template, but it’s expired, Smarty will run a single compile_check before regenerating the cache.
compile_dir
This is the name of the directory where compiled templates are located. By default this is %kernel.cache_dir%/smarty/templates_c. This directory must be writeable by the web server.
compile_id
Persistant compile identifier. As an alternative to passing the same $compile_id to each and every function call, you can set this $compile_id and it will be used implicitly thereafter. With a $compile_id you can work around the limitation that you cannot use the same $compile_dir for different $template_dirs. If you set a distinct $compile_id for each $template_dir then Smarty can tell the compiled templates apart by their $compile_id. If you have for example a prefilter that localizes your templates (that is: translates language dependend parts) at compile time, then you could use the current language as $compile_id and you will get a set of compiled templates for each language you use. Another application would be to use the same compile directory across multiple domains / multiple virtual hosts.
compile_locking
Compile locking avoids concurrent compilation of the same template. Compile locking is enabled by default.
compiler_class
Specifies the name of the compiler class that Smarty will use to compile the templates. The default is ‘Smarty_Compiler’. For advanced users only.
config_booleanize
If set to TRUE, config files values of on/true/yes and off/false/no get converted to boolean values automatically. This way you can use the values in the template like so: {if #foobar#}...{/if}. If foobar was on, true or yes, the {if} statement will execute. Defaults to TRUE.
config_dir
This is the directory used to store config files used in the templates. Default is %kernel.root_dir%/config/smarty.
config_overwrite
If set to TRUE, the default then variables read in from config files will overwrite each other. Otherwise, the variables will be pushed onto an array. This is helpful if you want to store arrays of data in config files, just list each element multiple times.
config_read_hidden
If set to TRUE, hidden sections ie section names beginning with a period(.) in config files can be read from templates. Typically you would leave this FALSE, that way you can store sensitive data in the config files such as database parameters and not worry about the template loading them. FALSE by default.
debug_tpl
This is the name of the template file used for the debugging console. By default, it is named debug.tpl and is located in the SMARTY_DIR.
debugging
This enables the debugging console. The console is a javascript popup window that informs you of the included templates, variables assigned from php and config file variables for the current script. It does not show variables assigned within a template with the {assign} function.
debugging_ctrl
This allows alternate ways to enable debugging. NONE means no alternate methods are allowed. URL means when the keyword SMARTY_DEBUG is found in the QUERY_STRING, debugging is enabled for that invocation of the script. If $debugging is TRUE, this value is ignored.
default_config_type
This tells smarty what resource type to use for config files. The default value is file, meaning that $smarty->configLoad('test.conf') and $smarty->configLoad('file:test.conf') are identical in meaning.
default_modifiers
This is an array of modifiers to implicitly apply to every variable in a template. For example, to HTML-escape every variable by default, use array('escape:"htmlall"'). To make a variable exempt from default modifiers, add the ‘nofilter’ attribute to the output tag such as {$var nofilter}.
default_resource_type
This tells smarty what resource type to use implicitly. The default value is file, meaning that {include 'index.tpl'} and {include 'file:index.tpl'} are identical in meaning.
default_config_handler_func
This function is called when a config file cannot be obtained from its resource.
default_template_handler_func
This function is called when a template cannot be obtained from its resource.
direct_access_security
Direct access security inhibits direct browser access to compiled or cached template files. Direct access security is enabled by default.
error_reporting
When this value is set to a non-null-value it’s value is used as php’s error_reporting level inside of display() and fetch().
escape_html
Setting $escape_html to TRUE will escape all template variable output by wrapping it in htmlspecialchars({$output}, ENT_QUOTES, SMARTY_RESOURCE_CHAR_SET);, which is the same as {$variable|escape:"html"}. Template designers can choose to selectively disable this feature by adding the nofilter flag: {$variable nofilter}. This is a compile time option. If you change the setting you must make sure that the templates get recompiled.
force_cache
This forces Smarty to (re)cache templates on every invocation. It does not override the $caching level, but merely pretends the template has never been cached before.
force_compile
This forces Smarty to (re)compile templates on every invocation. This setting overrides $compile_check. By default this is FALSE. This is handy for development and debugging. It should never be used in a production environment. If $caching is enabled, the cache file(s) will be regenerated every time.
inheritance_merge_compiled_includes

In Smarty 3.1 template inheritance is a compile time process. All the extending of {block} tags is done at compile time and the parent and child templates are compiled in a single compiled template. {include} subtemplate could also {block} tags. Such subtemplate could not compiled by it’s own because it could be used in other context where the {block} extended with a different result. For that reason the compiled code of {include} subtemplates gets also merged in compiled inheritance template.

Merging the code into a single compile template has some drawbacks. 1. You could not use variable file names in {include} Smarty would use the {include} of compilation time. 2. You could not use individual compile_id in {include}. 3. Seperate caching of subtemplate was not possible. 4. Any change of the template directory structure between calls was not necessarily seen.

Starting with 3.1.15 some of the above conditions got checked and resulted in an exception. It turned out that a couple of users did use some of above and now got exceptions.

To resolve this starting with 3.1.16 there is a new configuration parameter $inheritance_merge_compiled_includes. For most backward compatibility its default setting is true. With this setting all {include} subtemplate will be merge into the compiled inheritance template, but the above cases could be rejected by exception.

If $smarty->inheritance_merge_compiled_includes = false; {include} subtemplate will not be merged. You must now manually merge all {include} subtemplate which do contain {block} tags. This is done by setting the "inline" option. {include file='foo.bar' inline}

  1. In case of a variable file name like {include file=$foo inline} you must you the variable in a compile_id $smarty->compile_id = $foo;
  2. If you use individual compile_id in {include file=’foo.tpl’ compile_id=$bar inline} it must be used in the global compile_id as well $smarty->compile_id = $foo;

3. If call templates with different template_dir configurations and a parent could same named child template from different folders you must make the folder name part of the compile_id.

In the upcomming major release Smarty 3.2 inheritance will no longer be a compile time process. All restrictions will be then removed.

left_delimiter
This is the left delimiter used by the template language. Default is {.
locking_timeout
This is maximum time in seconds a cache lock is valid to avoid dead locks. The deafult value is 10 seconds.
merge_compiled_includes
By setting $merge_compiled_includes to TRUE Smarty will merge the compiled template code of subtemplates into the compiled code of the main template. This increases rendering speed of templates using a many different sub-templates. Individual sub-templates can be merged by setting the inline option flag within the {include} tag. $merge_compiled_includes does not have to be enabled for the inline merge.
php_handling
This tells Smarty how to handle PHP code embedded in the templates. There are four possible settings, the default being Smarty::PHP_PASSTHRU. Note that this does NOT affect php code within {php}{/php} tags in the template. Settings: Smarty::PHP_PASSTHRU - Smarty echos tags as-is; Smarty::PHP_QUOTE - Smarty quotes the tags as html entities; Smarty::PHP_REMOVE - Smarty removes the tags from the templates; Smarty::PHP_ALLOW - Smarty will execute the tags as PHP code.
plugins_dir
This is the directory or directories where Smarty will look for the plugins that it needs. Default is plugins/ under the SMARTY_DIR. If you supply a relative path, Smarty will first look under the SMARTY_DIR, then relative to the current working directory, then relative to the PHP include_path. If $plugins_dir is an array of directories, Smarty will search for your plugin in each plugin directory in the order they are given. While using the SmartyBundle you may add plugins by setting services tagged with smarty.extension. See section Extensions for more information.
right_delimiter
This is the right delimiter used by the template language. Default is }.
smarty_debug_id
The value of $smarty_debug_id defines the URL keyword to enable debugging at browser level. The default value is SMARTY_DEBUG.
template_dir
This is the name of the default template directory. If you do not supply a resource type when including files, they will be found here. By default this is %kernel.root_dir%/Resources/views. $template_dir can also be an array of directory paths: Smarty will traverse the directories and stop on the first matching template found. Note that the SmartyEngine included in this bundle already add the template directory of each registered Bundle.
trim_whitespace
Trim unnecessary whitespace from HTML markup.
trusted_dir
$trusted_dir is only for use when security is enabled. This is an array of all directories that are considered trusted. Trusted directories are where you keep php scripts that are executed directly from the templates with {include_php}.
use_include_path
This tells smarty to respect the include_path within the File Template Resource handler and the plugin loader to resolve the directories known to $template_dir. The flag also makes the plugin loader check the include_path for $plugins_dir.
use_sub_dirs
Smarty will create subdirectories under the compiled templates and cache directories if $use_sub_dirs is set to TRUE, default is FALSE. In an environment where there are potentially tens of thousands of files created, this may help the filesystem speed. On the other hand, some environments do not allow PHP processes to create directories, so this must be disabled which is the default. Sub directories are more efficient, so use them if you can. Theoretically you get much better perfomance on a filesystem with 10 directories each having 100 files, than with 1 directory having 1000 files. This was certainly the case with Solaris 7 (UFS)… with newer filesystems such as ext3 and especially reiserfs, the difference is almost nothing.

Contributing

Submitting bugs and feature requests

Bugs and feature requests are tracked on GitHub.

Coding Standards

When contributing to SmartyBundle you should follow the standards defined in the PSR-0, PSR-1 and PSR-2. documents.

Here’s a short example:

<?php
/**
* This file is part of NoiseLabs-SmartyBundle
*
* NoiseLabs-SmartyBundle is free software; you can redistribute it
* and/or modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* NoiseLabs-SmartyBundle is distributed in the hope that it will be
* useful, but WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with NoiseLabs-SmartyBundle; if not, see
* <http://www.gnu.org/licenses/>.
*
* Copyright (C) 2011-2013 Vítor Brandão
*
* @category    NoiseLabs
* @package     SmartyBundle
* @author      Vítor Brandão <vitor@noiselabs.org>
* @copyright   (C) 2011-2013 Vítor Brandão <vitor@noiselabs.org>
* @license     http://www.gnu.org/licenses/lgpl-3.0-standalone.html LGPL-3
* @link        http://www.noiselabs.org
*/

namespace NoiseLabs\Bundle\SmartyBundle;

/**
 * This class provides X.
 *
 * @author John Doe <john@example.com>
 */
class FooBar
{
    const SOME_CONST = 42;

    private $fooBar;

    /**
     * @param string $dummy Some argument description
     */
    public function __construct($dummy)
    {
        $this->fooBar = $this->transformText($dummy);
    }

    /**
     * @param string $dummy Some argument description
     * @return string|null Transformed input
     */
    private function transformText($dummy, $options = array())
    {
        $mergedOptions = array_merge($options, array(
            'some_default' => 'values',
        ));

        if (true === $dummy) {
            return;
        }
        if ('string' === $dummy) {
            if ('values' === $mergedOptions['some_default']) {
                $dummy = substr($dummy, 0, 5);
            } else {
                $dummy = ucwords($dummy);
            }
        }

        return $dummy;
    }
}

Structure

  • Add a single space after each comma delimiter;
  • Add a single space around operators (==, &&, …);
  • Add a blank line before return statements, unless the return is alone inside a statement-group (like an if statement);
  • Use braces to indicate control structure body regardless of the number of statements it contains;
  • Define one class per file - this does not apply to private helper classes that are not intended to be instantiated from the outside and thus are not concerned by the PSR-0 standard;
  • Declare class properties before methods;
  • Declare public methods first, then protected ones and finally private ones.
Naming Conventions
  • Use camelCase, not underscores, for variable, function and method names, arguments;
  • Use underscores for option, parameter names;
  • Use namespaces for all classes;
  • Suffix interfaces with Interface;
  • Use alphanumeric characters and underscores for file names;
Documentation
  • Add PHPDoc blocks for all classes, methods, and functions;
  • Omit the @return tag if the method does not return anything;
License
  • SmartyBundle is released under the LGPL-3 license, and the license block has to be present at the top of every PHP file, before the namespace.

Authors

Vítor Brandão - vitor@noiselabs.org ~ twitter.com/noiselabs ~ blog.noiselabs.org

See also the list of contributors who participated in this project.

Introduction

Installation

Basic Usage / Tips & Tricks

SmartyBundle Extensions

Major components: Assetic, Forms and Twitter-Bootstrap

Configuration Reference

Contributing to SmartyBundle: coding standards and API

API

SmartyBundle API is generated daily using ApiGen.

You can browse it here .

License

This bundle is licensed under the LGPL-3 License. See the LICENSE file for details.

Credits

Code

A big thanks to all SmartyBundle contributors and everyone who helped along the way.

Documentation

Author:Vítor Brandão (vitor@noiselabs.org)
Version:1.3.1
Date:Oct 07, 2018

Note

A lot of the content found in this documentation was “borrowed” from Smarty and Symfony2 documentation pages and websites. Credits goes to Smarty and Symfony authors and contributors.

Indices and tables

Table Of Contents