Useful Twig variables

Estimated reading: 2 minutes

When using Twig you will be using the same post parameters over and over again. Here’s a overview of some of the most useful parameters that are available.

Post Object

{{post.title}}
{{post.content}}
{{post.post_date}}
{{post.post_modified}}
{{post.thumbnail}}
{{post.link}}
{{post.parent}}
{{post.status}}
{{post.type}}
{{post.slug}}
{{post.date}}
{{post.author}}
{{post.name}}
{{post.menu_order}}
{{post.comment_count}}
{{post.modified}}

Post Terms Object

{{post.terms}}

{% for term in post.terms %}
    {{ term.id }}
    {{ term.slug }}
    {{ term.name }}
    {{ term.taxonomy }}
    {{ term.parent }}
{% endfor %}

Post Author Object

{{post.author}}

{% for item in post.author %}
    {{ item.object_type }}
    {{ item.name }}
    {{ item.display_name }}
    {{ item.description }}
    {{ item.avatar }}              (array)
    {{ item.first_name }}
    {{ item.last_name }}
    {{ item.user_nicename }}
    {{ item.user_email }}
    {{ item.user_url }}
{% endfor %}

Site Object

{{ site.name }}
{{ site.description }}
{{ site.url }}
{{ site.home_url }}
{{ site.site_url }}
{{ site.language }}

{{site.theme }}           (array)

{% for item in site.theme %}
    {{ item.name }}
    {{ item.version }}
    {{ item.parent }}
    {{ item.uri }}
{% endfor %}

User Object

{{ user.name }}
{{ user.first_name }}
{{ user.last_name }}
{{ user.nickname }}
{{ user.nicename }}
{{ user.wp_capabilities }}
{{ user.administrator }}
{{ user.wp_user_level }}
{{ user.url }}
{{ user.registered }}

Variables in Macros and templates: _self

_self references the current template name. A bit confusing at times but here’s how to use it:

{% macro first_macro( ) %}
{{ _self.second_macro( 'This is the second' ) }}
{% endmacro %}

{% macro second_macro( text ) %}
<h2>{{ text }}</h2>
{% endmacro %}

{{ _self.first_macro() }}

In order to call the macro called “second_macro” we first need to import the template _self into a variable.

The returned html for the template above would be:

<h2>This is the second</h2>

Variables in Macros and templates: _context

When using twig templates in Toolbox you can also use the macro functionality. Macro’s are the equivalent of a PHP function in Twig.

One major different though is scope. There is no global scope in twig, so you’ll have to pass in the parameters if they are needed in the macro.

Instead of passing lots of variables as seperate parameters that you need, you can pass in the _context variable. This variable holds all the variables that are accessible within the scope that is calling the macro.

{% macro mymacro( globalvars ) %}
    Value of the global variable pi is {{ globalvars.pi }}
{% endmacro %}

{% set pi = 3.14159 %}
{{ _self.mymacro( _context ) }}
Share this Doc

Useful Twig variables

Or copy link

CONTENTS