Skip to the content
Documentation

Re: Re: def using namespaces (2)

No ratings yet

Yes, but what if I want to define a variable in the 'root' or 'global' namespace?
The following does not work:

        {def $loaded='pippopippo'}        {set name=root $loaded='pippopippo'}

In this case $root:loaded outputs nothing!
g

Comments (4 historical)

Written by readers of the earlier documentation sites, kept as they were.

  1. How to define global variables

    Leif Arne Storset ·

    After some forum searching, trial and failure, I found out how to work with global variables. Apparently, 'root' means current template, and 'global' is for exchanging data between templates. :S
    You cannot declare a variable as global, so just declare it like a regular variable (definition is compulsory):

    {def $total_items=0}

    To define or set a global variable:

    {set scope='global' $total_items=0}

    To read a global variable:

    {$#total_items}

    To update a global variable, you naturally combine the above:

    {set scope='global' $total_items=$#total_items|inc()}
    1. Re: How to define global variables

      Olav Bringedal ·

      Thanks for your research.
      It really logical, but I had to try a few times before it got to me:
      You need to declare the variable in pagelayout.tpl to access it in templates on same or higher level than the one that sets it.

      1. Re: Re: How to define global variables

        Guillaume ·

        This doesn't work for me, i can set the var but i cannot get the value.

        1. Re: Re: Re: How to define global variables

          Gaetano ·

          If you have trouble using scopes or namespaces, a simpler solution is to use the "persistent_variable" var:
          - it is accessed as $persistent_variable in node templates
          - it can be set directly in any template without having to be def()ined first
          - it can be set() in an included template and it will be available in the including template
          - it will even be available in another template included after the one where it is set
          - it will be available in the pagelayout via $module_result.content_info.persistent_variable
          the only drawback is that it is not easy to use in custom modules.
          To store multiple values, just make it a hashmap containing all the desired values.
          Otoh if all you need to pass around between templates are strings, you might also investigate the set-block template function, which takes scope and namespace params. It works better than set.