首页 > 解决方案 > Zkoss 在 zhtml 中使用模板

问题描述

再会。这是我的zhtml

<x:html xmlns="http://www.zkoss.org/2005/zul"
        xmlns:x="xhtml"
        src="/components/public-page-template.html">
  <div viewModel="@id('vm') @init('TestViewModel')">
    <div children="@init(vm.testList)">
      <template name="children">
        <checkbox label="@load(each)"/>
      </template>
    </div>
  </div>
</x:html>

并查看模型

public class TestViewModel {
  public List<String> getTestList(){
    return List.of("one", "two", "three");
  }
}

我希望在呈现的 html 中看到 3 个复选框,但我得到 3 个跨度

<div id="mXBQ2" class="z-div">
  <div id="mXBQ3" class="z-div">
    <span id="mXBQ4" class="z-label">one</span>
    <span id="mXBQ5" class="z-label">two</span>
    <span id="mXBQ6" class="z-label">three</span>
  </div>
</div>

无论我在模板中放什么,我都会得到 3 个跨度,模板会被完全忽略。但是如果把 zhtml 改成 zul

<?xml version="1.0" encoding="UTF-8"?>
<?variable-resolver class="org.zkoss.spring.DelegatingVariableResolver" ?>

<div xmlns="http://www.zkoss.org/2005/zul" viewModel="@id('vm') @init('TestViewModel')">
  <div children="@load(vm.testList)">
    <template name="children">
      <checkbox label="@load(each)"/>
    </template>
  </div>
</div>

然后模板按预期工作,我在结果 html 中看到 3 个复选框。

如何使模板在我的 zhtml 中工作?

标签: javazk

解决方案


我想,您缺少的是该<template>元素不是 zul 组件的事实(而是那些控制如何创建组件的特殊 ZUML 元素)。运行您的示例代码时,我得到一个异常......这表明出了什么问题(或多或少清楚)。

org.zkoss.zk.ui.metainfo.DefinitionNotFoundException: 
    Component definition not found: template in [LanguageDefinition: xul/html]

相反,您必须为这些特殊元素声明并使用相应的命名空间“zk”(.zhtml 文件与 .zul 文件具有不同的解析规则)

<x:html xmlns="http://www.zkoss.org/2005/zul"
        xmlns:x="xhtml"
        xmlns:zk="zk"
        src="/components/public-page-template.html">
...
   <zk:template>
   ...
   </zk:template>

除此之外,我不确定src根元素的属性是做什么的x:html。在我的测试中,它被清楚地呈现给了 DOM 元素,我假设您有自己的自定义处理来处理它。


推荐阅读