【问题标题】:Polymer: how to replace tag name depend on attribute?聚合物:如何根据属性替换标签名称?
【发布时间】:2015-01-05 01:08:20
【问题描述】:

我有这样的模板

<template>
    <button class="y-button" id="el" disabled?="{{disabled !== undefined}}">
        <span class="y-button__text"><content></content></span>
    </button>
</template>

如何将标签名称更改为另一个(例如&lt;a&gt;)取决于某些属性,例如 &lt;my-button url="http://example.org"&gt;&lt;/my-button&gt;?

我试过了

<template>
  <{{tagName}}></{{tagName}}>
</template>

但它不起作用。

【问题讨论】:

  • 我不太明白你的问题。您是否尝试基于模型动态创建元素?如果是这样,您可以简单地使用元素的 javascript 来处理它。让我知道更多细节,以便我能更好地为您提供帮助。
  • 我在模板中有一个很大的声明标签:按钮几个处理程序,具有数据绑定的类。现在我需要将标签名称

标签: polymer


【解决方案1】:

您可以使用injectBoundHTML

var tag = 'x-el';
var html = '<' + tag + ' item="{{item}}"></' + tag + '>';
this.injectBoundHTML(html, this.$.container);

<script src="http://www.polymer-project.org/webcomponents.min.js"></script>
<script src="http://www.polymer-project.org/polymer.js"></script>

<polymer-element name="x-el" attributes="item" noscript>
  <template>
    {{item.name}}
  </template>
</polymer-element>

<polymer-element name="my-element">
  <template>
    <div id="container"></div>
  </template>
  <script>
    Polymer({
      ready: function() {
        this.item = {name: 'John Smith'};
        
        var tag = 'x-el';
        var html = '<' + tag + ' item="{{item}}"></' + tag + '>';
        this.injectBoundHTML(html, this.$.container);
      }
    });
  </script>
</polymer-element>

<my-element></my-element>

【讨论】:

    【解决方案2】:

    您不能通过数据绑定来做到这一点。绑定表达式只允许在标记的文本内容或属性值中:

    https://www.polymer-project.org/docs/polymer/binding-types.html#node-bindings

    您也不能使用数据绑定插入整个标签,因为数据绑定表达式的内容在插入之前是 HTML 转义的。见:

    https://www.polymer-project.org/docs/polymer/expressions.html#expression-syntax

    “您不能使用表达式插入 HTML。为避免 XSS 问题,表达式的输出是 HTML 转义,然后作为绑定的值插入。”

    如果你只有两个可能的标签,你可以使用条件模板语法:

    <template if="{{condition}}">
      <tagOne></tagOne>
    </template>
    <template if="{{! condition}}">
      <tagTwo></tagTwo>
    </template>
    

    对于更复杂的情况,您可能需要使用 @skmvasu 建议的 JavaScript 和 innerHTML。如果您需要在插入的 HTML 内部激活数据绑定,则可以使用 injectBoundHTML 方法:

    https://www.polymer-project.org/docs/polymer/databinding-advanced.html#boundhtml

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-20
      • 1970-01-01
      • 1970-01-01
      • 2021-09-26
      • 1970-01-01
      相关资源
      最近更新 更多