Thymeleaf composite components

两盒软妹~` 提交于 2019-12-22 18:19:35

问题


Is there any way of making composite components (like in JSF) using Thymeleaf? I found out how to send parameters to fragments that can be retrieved using the expression language. But I haven't figured out how to send markup to fragments like you can in JSF.

For example, I have several pages that have very similar menus on the left. I would like to be able to use a single fragment on all my pages, but passing some markup to be displayed at the bottom of the menu. Some pages have to display text at the bottom, some have to display text, for example, it's actually more complicated than that.

<div class="menu" th:frament="menu">
    <a th:text="${menuItem1}"></a>
    <a th:text="${menuItem2}"></a>
    <a th:text="${menuItem3}"></a>
    <markup sent as parameter /> <!-- how do I do this? -->
</div>



<div th:substitueBy="template :: menu" th:with="menuItem1=item1, menuItem2:item2, menuItem3:item3">
    <markup to be sent as parameter /> <!-- this does not work -->
</div>

回答1:


I also wanted to create composite components with exchangeable content. That's why I developed the thymeleaf-component-dialect.

With this dialect, you can write components like this:

Create a component (a thymeleaf fragment) with a <tc:content/> tag

<div th:frament="menu">
    <a th:text="${menuItem1}"></a>
    <a th:text="${menuItem2}"></a>
    <a th:text="${menuItem3}"></a>
    <tc:content></tc:content>
</div>

Use the component

<tc:menu>
    <h1>Some Header</h1>
    <p>Lorem ipsum dolor sit amet</p>
</tc:menu>

The result will be

<div>
    <a>Menu Item 1 Text</a>
    <a>Menu Item 2 Text</a>
    <a>Menu Item 3 Text</a>
    <h1>Some Header</h1>
    <p>Lorem ipsum dolor sit amet</p>
</div>

The dialect is new and is still in alpha state. Feedback is welcome.




回答2:


You can do something like this:

But you will have to write all menu container attributes to every page you use it.

I dont really like this way, but I think it should works :p

Template:

<div th:frament="menu">
    <a th:text="${menuItem1}"></a>
    <a th:text="${menuItem2}"></a>
    <a th:text="${menuItem3}"></a>
</div>

Page:

<div class="menu">
    <div th:include="template :: menu" 
         th:remove="tag" 
         th:with="menuItem1=item1, menuItem2:item2, menuItem3:item3" />
    <more markup/>
</div>


来源:https://stackoverflow.com/questions/17200971/thymeleaf-composite-components

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!