javazk

Zkoss using template in zhtml


Good day. Here is my 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>

And view model

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

I expect to see 3 checkboxes in rendered html, but I get 3 spans

<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>

No matter what I put inside template I get 3 spans, template is completely ignored. But if change zhtml to 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>

then template is working as expected and I see 3 checkboxes in result html.

How can I make template work in my zhtml?


Solution

  • I guess, what you're missing is the fact that the <template> element is not a zul component (instead those are special ZUML elements which control how components are created). When running your example code I get an exception ... which indicates what's wrong (more or less clearly).

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

    Instead you have to declare and use the according namespace "zk" for these special elements (.zhtml files have different parsing rules than .zul files)

    <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>
    

    Besides that I am not sure what the src attribute at the root element x:html does. In my tests it was plainly rendered to the DOM element, I assume you have your own custom processing handling that.