htmlgoogle-closure-templatessoy-templates

Closure Templates: setting global variable from passed paramater in soy file


is there a way to set global variables in the .soy file to parameters passed in from .html? So that all templates would be able to access the global variables to avoid the redundancy of repassing the same parameters to each template.

For example something that would work like this:

HTML:

document.write(wet4.gcweb.setGlobal({templatedomain:"example.ca"}));    

soy:

/**
 * Test.
 * @param templatedomain 
 */
{template .setGlobal}
globalVariable = $templatedomain
{/template}

and globalVariable could be accessed from all other templates


Solution

  • My experience with Google Closure Templates is limited to the Java backend in Atlassian plugin development, however, the templates use a reserved variable for global data: $ij. The following is taken from the Injected Data section of the documentation:

    Injected data is data that is available to every template. You don't need to use the @param declaration for injected data, and you don't need to manually pass it to called subtemplates.

    Given the template:

    {namespace ns autoescape="strict"}
    
    /** Example. */
    {template .example}
      foo is {$ij.foo}
    {/template}
    

    In JavaScript, you can pass injected data via the third parameter.

    // The output is 'foo is injected foo'.
    output = ns.example(
        {},  // data
        null,  // optional output buffer
        {'foo': 'injected foo'})  // injected data
    

    In Java, using the Tofu backend, you can inject data by using the setIjData method on the Renderer.

    SoyMapData ijData = new SoyMapData();
    ijData.put("foo", "injected foo");
    
    SoyTofu tofu = ...;
    String output = tofu.newRenderer("ns.example")
        .setIjData(ijData)
        .render();
    

    Injected data is not scoped to a function like parameters. The templates below behave in the same way as the ".example" template above despite the lack of any data attribute on the call tag.

    {namespace ns autoescape="strict"}
    
    /** Example. */
    {template .example}
      {call .helper /}
    {/template}
    
    /** Helper. */
    {template .helper private="true"}
      foo is {$ij.foo}
    {/template}