2

我正在制作一个模板助手,它将内联 SVG 图标插入到我的模板中。我想传递一个参数来添加一个额外的 CSS 类(它将用于更改默认大小、颜色等)。

我的期望

<button> 
  <svg viewBox="0 0 78 73" class="svg-icon svgWhite" version="1.1" ...>
    <polygon id="icon-star" points="39 ... 60">
    </polygon>
  </svg>
</button>

我得到什么

<button> 
  "[object Object]" 
  <svg viewBox="0 0 78 73" class="svg-icon" version="1.1" ...>
    <polygon id="icon-star" points="39 ... 60">
    </polygon>
    <!--[object Object]-->
  </svg>
</button>

我的模板

<template name="whatever">
  <button>{{{icon.star svgWhite}}}</button>
</template>

我的模板助手

Template.registerHelper('icon', {
  star:   function (userClass, userWrapper) {
    var wrapper = (userWrapper == undefined) ? "i" : userWrapper;
    var addlClass = (userClass == undefined) ? "" : ", " + userClass;
    var svgWidth = 78;
    var svgHeight = 73;

    var svgCode = '<polygon id="icon-star" points="39 .... 60"></polygon>';

    var icon = '<'+wrapper+'>' +
      '<svg viewBox="0 0 ' + svgWidth + ' ' + svgHeight + '" ' +
      'class="svg-icon' + addlClass + '" ' +
      svgConfig + '>' + svgCode + '</' + wrapper + '>';

    return icon
  }
});

参考:https ://github.com/meteor/meteor/tree/devel/packages/spacebars#helper-arguments

4

1 回答 1

3

您的模板助手注册看起来已损坏,我认为您正在尝试使用过于复杂的方式来实现简单的事情。

当您开始使用三方括号语法并在 javascript 中编写 HTML 时,您知道您可能做错了:您可能应该使用模板包含来执行您需要的操作。

首先,我们定义父模板,它将包含一个我们可以使用属性配置的子模板(这些属性将充当子模板的数据上下文)。

<template name="svgButton">
    <button type="button">
        {{> svgIcon class="svg-white"}}
    </button>
</template>

然后我们定义子模板,我们可以使用从父模板传来的属性。

<template name="svgIcon">
    <svg viewBox="0 0 {{width}} {{height}}" class="svg-icon {{class}}">
        {{! warning, polygon is a self closing tag like img}}
        <polygon id="icon-star" points="..." />
    </svg>
</template>

我们可以定义帮助器,如果存在数据上下文的值,或者默认值:

Template.svgIcon.helpers({
  width:function(){
    return this.width || 78;
  },
  height:function(){
    return this.height || 73;
  }
});

因此,我们可以使用此表单包含子模板以进行高级定制:

{{> svgIcon class="svg-whatever" width="16" height="16"}}

编辑 :

当我有 20 多个图标模板时会发生什么。那么我是否有 20 多个具有可重复功能(不是 DRY)的模板助手?

这是我将使用的方法:

首先,将所有图标 svg 内容定义为不同的模板。

<template name="svgIconStarContent">
  <polygon id="icon-star" points="..."/>
</template>

{{! repeat 20 times...
    but this is DRY compliant because each time this is a different icon}}

然后我们可以使用UI.dynamic基于参数名称包含正确的模板。

https://www.discovermeteor.com/blog/blaze-dynamic-template-includes/

<template name="svgIcon">
    <svg viewBox="0 0 {{width}} {{height}}" class="svg-icon {{class}}">
        {{> UI.dynamic template=svgIconContent}}
    </svg>
</template>

最后,在父模板中,我们可以传递我们想要动态插入的模板的名称,这样当使用不同的值调用时,图标的内容可能会有所不同。

{{> svgIcon svgIconContent="svgIconStarContent"}}
于 2014-09-29T17:30:29.020 回答