首页 > 解决方案 > TemplateRenderer 返回 null (Vaadin Flow / 14.1)

问题描述

对于我的其中一列,我Grid使用了一个TemplateRenderer(显示一个图标以提示该行可能存在问题):

grid.addColumn(TemplateRenderer.<T>of("<iron-icon icon='[[item.icon.name]]' title='[[item.icon.tooltip]]' style='width: 1em;'></iron-icon>")
    .withProperty("icon", item -> StatusHint.of(item))
    ...
    ;

对于某些项目,此模板不相关(没有问题),因此属性“icon”为null. 结果是这个 HTML: <iron-icon style="width: 1em;" title="undefined"></iron-icon>
另请注意,未显示“图标”属性且未定义标题属性?!

尽管浏览器没有显示任何内容,但毫无头绪的 HTML 代码是丑陋的恕我直言(不知道是否还有性能损失)。

一个空的单元格或<div></div>看起来好多了。

我如何做到这一点?API 没有给我任何提示。

标签: vaadinvaadin-flow

解决方案


这有点复杂,但您可以使用 Polymer 的dom-if模板来创建条件子模板,以应对不能只绑定属性的情况。这是一个根据 Person 的年龄是偶数还是奇数打印“偶数”或“奇数”的示例:

grid.addColumn(
      TemplateRenderer.<Person>of(
      "<template is='dom-if' if='[[item.even]]'><b>even</b></template><template is='dom-if' if='[[!item.even]]'><i>odd</i></template>"
      ).withProperty("even", p -> {
            int age = p.getAge();
            return age % 2 == 0;
      }))
      .setHeader("Is age even or odd?");

推荐阅读