Skip to content
This repository was archived by the owner on Feb 17, 2022. It is now read-only.

7.x 2.x twig recipes

Andy Truong edited this page Apr 6, 2014 · 17 revisions

Do not cache Twig template

Twig compiled templates are cached by default. To auto refresh the compiled template, in settings.php, add this line:

define('AT_DEBUG', TRUE);

Do not enable this on production sites.

Call service method:

{# call: Class_Name::getValue() #}
{{ fn__at_container('server.name').value() }}
{{ 'Is same to: ' ~ fn__at_container('server.name').getValue() }}

Get available variables

{{ attribute(get_defined_vars(), 'context')|kpr }}

Render View with template:

{{ 'view_name'|drupalView({template: '@my_module/templates/views/view_name.html.twig'}) }}

To minimize your time on view template, just extends to default view template:

{% extends '@at_base/templates/views_view.html.twig' %}

{% block debug %}
  {{ attribute(get_defined_vars(), 'context')|dsm }}
{% endblock %}

Render entity with custom template

{% set o = { template: '@atest_base/templates/entity/user.html.twig' } %}
{{ 'user:1'|drupalEntity(o) }}

Cache

Cache function call

{# Simple function #}
{% set options = { cache_id: 'atestTwigCache:1' } %}
{{ 'atest_base_hello' | cache(options) }}

{# Static method #}
{% set options = { cache_id: 'atestTwigCache:1' } %}
{{ 'At_Base_Test_Class::helloStatic' | cache(options) }}

{# Callback with argument #}
{% set callback = { callback: 'atest_base_hello', arguments: ['Andy Truong'] } %}
{{ callback | cache(options) }}

Cache service call

{% set options = { cache_id: 'atestTwigCache:1' } %}
{{ 'atest_base.service_1:hello' | cache(options) }}

/at/twig

A page for you to debug Twig templates.

Lazy functions/filters

Simple function

{# Call trim() #}
{{  fn__trim('  Drupal 7  ')  }}
{{  '  Drupal 7  '|fn__trim  }}

Static method

{# Call At_Base_Test_Class::helloStatic() #}
{{  'Drupal 8'|At_Base_Test_Class__class__helloStatic  }}
{{  At_Base_Test_Class__class__helloStatic('Drupal 8')  }}

Method on constructive class

{# $obj = new At_Base_Test_Class('PHP'); $obj->helloProperty(); #}
{{  'PHP'|At_Base_Test_Class__obj__helloProperty  }}
{{  At_Base_Test_Class__obj__helloProperty('PHP')  }}

Class under namespace

{# Drupal\atest_base\Service_1::helloStatic('Namespace') #}
{{  'Namespace'|ns_Drupal__atest_base__Service_1__class__helloStatic  }}
{{  ns_Drupal__atest_base__Service_1__class__helloStatic('Namespace')  }}

Clone this wiki locally