Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to access variables like arrays or objects in drupal template file?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 646
    Comment on it

    In the basic twig syntax tutorials we got to know about printing the simple variables like {{ variable }},

    but if we need to print an array or object and accessing them.

     

    Lets see how can we do it.

     

    To know the behavior of the parameter use any inspect to know whether the parameter is a key of the array or property of the object.

     

    we can use dot operator to access the items from the object or arrays.

     

    we need to use {{}} to print the parameter and if it is used in the condition then we need to use {% %}.

     

    for example :

     

    {% if page.highlighted %}
        <div class="highlighted">
            <aside>    
                {{ page.highlighted }}
            </aside>
        </div>
    {% endif %}

     


    if we need to access the key outside of the for loop using the dot operator with a numeric index.

     

    for example : {{ variable.0 }}

     

    We can use the square brackets too as {{ variable['key'] }} i.e.,  {{ variable[0] }}

     

    Twig uses the dot(".") operator to access the attributes on variables for the convenient purpose.

     

    The twig matches the variable going through a series of logics and check these are the following things that happens behind:

     

    1- The twig engine checks if the variable is array,.
    2- If not then it checks if it is an object with valid property.
    3- If not, then it checks if an object and a valid method.
    4- if not, then is it an object with getbar as a valid method.   
    5- if not, then is it an object with isBar as a valid method.
    6- Finally if it doesn't find any returns null.

     

    In template design we don't need to worry about the different syntaxes of array and objects.

    We just use the dot(".").

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: