html

Jmix 提供了一组与标准 HTML 元素对应的 HTML 组件。如果仍未包含你需要的元素,或者希望直接使用原生 HTML,可以用 html 组件。该组件支持渲染通过字符串、CDATA 或文件提供的 HTML。

  • XML 元素:html

  • Java 类:Html

基本用法

以下示例展示了如何通过消息包的字符串提供 HTML 内容:

html basic
<html content="msg://html.content"/>
messages.properties
com.company.onboarding.view.component.html/html.content=\
<main>\
  <h1>Main Content</h1>\
  <p>This is the main content area.</p>\
    <div>\
      <h2>Section 1</h2>\
      <p>This is the first section of the main content.</p> \
    </div>\
    <div>\
      <h2>Section 2</h2>\
      <p>This is the second section of the main content.</p>\
    </div>\
</main>

通过 CDATA(字符数据)也可以提供相同的 HTML 内容:

<html id="html">
    <content>
        <![CDATA[
        <main>
            <h1>Main Content</h1>
            <p>This is the main content area.</p>
            <div>
                <h2>Section 1</h2>
                <p>This is the first section of the main content.</p>
            </div>
            <div>
                <h2>Section 2</h2>
            <p>This is the second section of the main content.</p>
            </div>
        </main>
    ]]>
    </content>
</html>

这种方式可以保证 HTML 代码不会被当做 XML 的内容进行解析,从而能正确显示。

HTML 代码中,只能包含一个根元素,例如,<header><footer><main><div>。根元素内可以有任意个 <div> 元素用于显示内容。

文件

HTML 代码也可以用下列方法之一通过文件提供。

静态资源

文件可以由应用程序静态托管。

默认情况下,静态内容托管在 classpath 的 /static/public/resources/META-INF/resources 目录。详情参考: Spring Boot 文档

假设文件位于:/src/main/resources/META-INF/resources/html/html-file.html,则可以这样使用:

<html id="staticHtml" file="META-INF/resources/html/html-file.html"/>

流资源

HTML 代码还可以通过文件的 InputStream 提供,然后组件可以使用这个流进行初始化。

该组件不能通过 UiComponents bean 创建,因为其不具有无参数构造器。
protected static final String SRC_PATH = "META-INF/resources/html/html-file.html";
@Autowired
private Resources resources;

@Subscribe
public void onInit(final InitEvent event) {
    InputStream resourceAsStream = resources.getResourceAsStream(SRC_PATH);
    Html html = new Html(resourceAsStream);
}

CSS 属性

使用 css 属性声明式添加 CSS 样式。

<html file="META-INF/resources/html/html-file.html" css="background-color: grey;"/>

或者,也可以在 应用程序的主题中添加自定义的 CSS 样式。

XML 属性

content

指定组件需要渲染的 HTML 内容,可以是消息包内的键值或者 CDATA。

file

指定获取 HTML 内容的文件路径。

事件和处理器

在 Jmix Studio 生成处理器桩代码时,可以使用 Jmix UI 组件面板的 Handlers 标签页或者视图类顶部面板的 Generate Handler 添加,也可以通过 CodeGenerate 菜单(Alt+Insert / Cmd+N)生成。