google-closuregoogle-closure-templates

How do I load dependencies in a soy template?


In my Google Closure code, I made an enum denoting names of CSS classes and want to use this enum in my soy template:

/**
 * Lists a single widget.
 * @param widget The widget to be listed.
 */
{template .singleWidgetListing}
<div class='{app.ui.ClassNames.WIDGET_LISTING}'>
  <span class='{app.ui.ClassNames.WIDGET_LISTING_ITEM}'>{$widget.title}</span>
</div>
{/template}

I tried goog.require('app.ui.ClassNames'); at the top of the soy template file to no avail. What is the standard way to do this?


Solution

  • The recommended approach is avoid referencing globals in Closure Templates:

    Note: Avoid using render-time globals unless absolutely necessary, because it makes for tight coupling between your template and your runtime environment.

    A template parameter should be used instead:

    {namespace myapp}
    
    /**
     * Lists a single widget.
     * @param widget The widget to be listed.
     * @param classNames Map of CSS classes for styling widgets.
     */
    {template .singleWidgetListing}
      <div class="{$classNames.WIDGET_LISTING}">
        <span class="{$classNames.WIDGET_LISTING_ITEM}">{$widget.title}</span>
      </div>
    {/template}
    

    The template would then be called from JavaScript as follows:

    myapp.singleWidgetListing(
        {widget: myWidgetInstance, classNames: app.ui.ClassNames});
    

    See Using Closure Templates in JavaScript.