Monday, May 04, 2015

[Symfony] Template

Render a template In controller action:
       return $this->render(
           'AcmeDemoBundle:Random:index.html.twig',
           array('number' => $number)
       );
The controller renders the AcmeDemoBundle:Random:index.html.twig template, which uses the following naming convention:
BundleName:ControllerName:TemplateName
This is the logical name of the template, which is mapped to a physical location using the following convention.
/path/to/BundleName/Resources/views/ControllerName/TemplateName
In this case, AcmeDemoBundle is the bundle name, Random is the controller, and index.html.twig the template.


Twig defines three types of special syntax:

{{ ... }}
"Says something": prints a variable or the result of an expression to the template.
To display something, use {{obj.member}} notation; 
{% ... %}
"Does something": a tag that controls the logic of the template; it is used to execute statements such as for-loops for example.
To control the flow or manipulate data, use
{% control statement or manipulation statement %}
{# ... #}
"Comment something"
To check for syntax errors in Twig templates using the twig:lint console command:
# You can check by filename:
$ php app/console twig:lint app/Resources/views/article/recent_list.html.twig
# or by directory:
$ php app/console twig:lint app/Resources/views



  • {% extends %} can be used to extend the page layout from a parent (base) layout. It is very useful for page design. i.e.
    {% extends '::base.html.twig' %}
     The parent template, ::base.html.twig, is missing both the BundleName and ControllerName portions of its name (hence the double colon (::) at the beginning). This means that the template lives outside of the bundle and in the app directory.
If you need to get the content of a block from the parent template, you can use the {{ parent() }} function. 
  • To include a tempate. i.e:
{{ include (‘AppBundle:Default:sidebar.html.twig', {‘para1’: para1}) }}
  • {% block blockname %}...{% endblock %} replaces the blockname content in the parent layout with your own content.
  • {{path(...)}} is used to generate URIs matching that route in the template. It is a very important helper function that everyone will use. Please also note how the parameters of that route are passed.
  • {% for ... in ... %} is used to iterate the result set. It is also very commonly used.
  • {% set ... %} is used to set a local variable.
  • To embedding the result of an entire controller from your template:
  •     {# app/Resources/views/base.html.twig #}

    {# ... #}

        {{ render(controller(
           'AcmeArticleBundle:Article:recentArticles',
           { 'max': 3 }
        )) }}

    When using a controller instead of a URL, you must enable the Symfony fragments configuration:
        # app/config/config.yml
        framework:
            # ...
            fragments: { path: /_fragment }


  • The rest is regular HTML.


Since the prod environment is optimized for speed; the configuration, routing and Twig templates are compiled into flat PHP classes and cached. When viewing changes in the prod environment, you'll need to clear these cached files and allow them to rebuild:
                   
$ php app/console cache:clear --env=prod --no-debug

Linking to Assets

Templates also commonly refer to images, JavaScript, stylesheets and other assets.
Symfony provides a dynamic option via the asset Twig function:
<img src="{{ asset('images/logo.png') }}" alt="Symfony!" />

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

If you need absolute URLs for assets, you can set the absolute argument to true:
<img src="{{ asset('images/logo.png', absolute=true) }}" alt="Symfony!" />

Global Template Variables

During each request, Symfony will set a global template variable app in both Twig and PHP template engines by default. The app variable is a GlobalVariables instance which will give you access to some application specific variables automatically:
app.security    The security context.
app.user    The current user object.
app.request    The request object.
app.session    The session object.
app.environment    The current environment (dev, prod, etc).
app.debug    True if in debug mode. False otherwise.

Username: {{ app.user.username }}
{% if app.debug %}
    Request method: {{ app.request.method }}
    Application Environment: {{ app.environment }}
{% endif %}

Overriding Bundle Templates

When the AcmeBlogBundle:Blog:index.html.twig is rendered, Symfony actually looks in two different locations for the template:
  1. app/Resources/AcmeBlogBundle/views/Blog/index.html.twig
  2. src/Acme/BlogBundle/Resources/views/Blog/index.html.twig
To override the bundle template, just copy the index.html.twig template from the bundle to app/Resources/AcmeBlogBundle/views/Blog/index.html.twig.

Reference:

Symfony Templating 

No comments: