如何在 UI5 中为文本添加换行符?

How to add a line break to text in UI5?

转义字符 \n 和 Unicode 字符 \u000a 仅在 JavaScript 中有效。但是,我正在尝试在 XML 视图中添加一个换行符,如下所示。但不起作用:

<u:TimelineItem text="First Line\n SecondLine" />

You can use the embeddedControl aggregation to use the text control inside TimelineItem

<u:TimelineItem>
      <u:embeddedControl><Text text="First Line\n SecondLine"></Text></u:embeddedControl>
</u:TimelineItem>

文本控件中的新行可以添加以下字符:

  • 在 XML 次观看或 XML 次片段中:

    • 换行&#10;&#x0A;
    • 推荐:* 结合马车return&#13;&#10;&#x0D;&#x0A;
  • 在 JSi18n.properties 文件中:

    • 换行\n\u000a.

    • 推荐:* 结合马车return\r\n\u000d\u000a.

    • 或者,考虑使用 template literals 而不是手动连接上述字符(即只需将 "..." 替换为 <strong>`</strong>...<strong>`</strong>).

  • 一些 UI5 控件允许开箱即用 HTML tag <br>(在 XML 中:&lt;br>):

* 请参阅 Issues with different newline formats。对于大多数互联网协议,建议使用 Carriage Return 组合。


这是 sap.suite.ui.commons.TimelineItem* 和 sap.m.Text:

的 UI5 演示

globalThis.onUI5Init = () => sap.ui.require([
  "sap/ui/core/mvc/XMLView",
  "sap/m/Text",
], async (XMLView, Text) => {
  "use strict";
  
  const view = await XMLView.create({
    definition: `<mvc:View xmlns:mvc="sap.ui.core.mvc" height="100%">
      <App xmlns="sap.m" autoFocus="false">
        <Page showHeader="false" class="sapUiResponsiveContentPadding">
          <commons:TimelineItem xmlns:commons="sap.suite.ui.commons"
            text="Multiline supported&#10;in Timeline items (XML)"
          />
          <HBox id="myBox" justifyContent="SpaceAround">
            <Text
              text="This&#10;is&#x0A;a&#13;&#10;text (created in XML view)!"
              renderWhitespace="true"
            />
          </HBox>
        </Page>
      </App>
    </mvc:View>`,
  });
  
  const textCreatedInJS = new Text({
    renderWhitespace: true,
    text: "And this\nis\u000aanother\r\ntext (created in JS)!",
  });
  view.byId("myBox").addItem(textCreatedInJS);
  view.placeAt("content");
});
<script id="sap-ui-bootstrap"
  src="https://ui5.sap.com/resources/sap-ui-core.js"
  data-sap-ui-libs="sap.ui.core,sap.m,sap.suite.ui.commons"
  data-sap-ui-theme="sap_fiori_3"
  data-sap-ui-oninit="onUI5Init"
  data-sap-ui-async="true"
  data-sap-ui-compatversion="edge"
  data-sap-ui-excludejquerycompat="true"
  data-sap-ui-xx-waitfortheme="init"
></script>
<body id="content" class="sapUiBody"></body>

* TimelineItem 在早期版本的 UI5 中有一个错误阻止多行。根据他们的 1.44.5 更新日志:

[FIX] sap.suite.ui.commons.Timeline: Rendering of multiline text improved


如果使用控件 sap.m.Text,请记住启用属性 renderWhitespacewrapping 以便在 DOM 中呈现新行。


对于 UI5 控件开发人员

渲染DOM中的文本可以通过API .text(/*...*/) from the RenderManager. That API, however, doesn't necessarily apply newlines even if the text contains the above mentioned line break characters. In that case, the white-space实现属性pre-line可以应用于控件的CSS样式:

.myControlWithText {
  /* ...; */
  white-space: pre-line; /* Allows line break characters to be applied */
}