Вопрос

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?

Это было полезно?

Решение

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.

Другие советы

Also consider passing in the map of CSS classes into your top-level template as injected data (https://developers.google.com/closure/templates/docs/concepts#injecteddata) so that you don't have to pass it through to subtemplates that need it.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top