Show TOC

XML TemplatingLocate this document in the navigation structure

The XML templating concept enables you to use an XML view as a template. This template is transformed by an XML preprocessor on the source level, the XML DOM, at runtime just before an SAPUI5 control tree is created from the XML source.

The label texts and binding paths in the example below come from SAP Annotations for OData Version 2.0 (http://www.sap.com/Protocols/SAPData) such as sap:semantics, and from OData Version 4.0 annotations such as com.sap.vocabularies.UI.v1.Badge. Much more complex tasks than shown in this simple example are possible.

The transformation happens if a preprocessor for XML is called when the view is created, see lines 2 and 3 in the Calling the XML Preprocessor example. This preprocessor can be given one or more models along with a corresponding binding context, see lines 4 and 7; this concept exists for any SAPUI5 control's constructor. Typically, an OData model's meta model is given, along with the meta context corresponding to a data path. XML templating operates on meta data. It can not wait for data that is loaded asynchronously or any other asynchronous events. If the data changes, the XML templating can not be executed again. This is due to the processing time. Only the resulting bindings are evaluated again.

In the example, sPath = "/ProductSet('HT-1021')/ToSupplier" and the corresponding meta context point to "/dataServices/schema/0/entityType/0" (the entity type BusinessPartner). The resulting view is bound to the data path within the OData model in order to display the supplier of that product.

Example:

Calling the XML Preprocessor
1  var oTemplateView = sap.ui.view({
2      preprocessors: {
3        xml: {
4          bindingContexts: {
5            meta: oMetaModel.getMetaContext(sPath)
6          },
7          models: {
8            meta: oMetaModel
9          }
10       }
11     },
12     type: sap.ui.core.mvc.ViewType.XML,
13     viewName: "sap.ui.core.sample.ViewTemplate.tiny.Template"
14   });
15 
16 oTemplateView.setModel(oModel);
17 oTemplateView.bindElement(sPath);
The XML preprocessor traverses the view's XML DOM in a depth-first, parent-before-child manner and does the following:
  • All XML attributes which represent an available binding, that is, a binding based only on models available to the preprocessor, are replaced by the result of that binding. Formatters and so on can be used as with any SAPUI5 binding.

  • XML fragments are inlined; that is, the reference is replaced by the fragment's XML DOM and preprocessing takes place on that DOM as well.

  • The preprocessing instructions <template:with>, <template:if> and <template:repeat> are processed.

Example:

Component.js

In the Explored app, see the simple example XML Templating: minimal sample based on OData Version 4.0 annotations. It consists of the following three pieces:

  • A component controller that creates an OData model (line 17), waits for the meta model to be loaded (line 28) and then creates a template view (line 29) as its content. A preprocessor for XML is requested (line 31) and settings are passed to it, namely the meta model and the binding context that identifies the starting point within that model. The resulting view is bound to the actual data (model and path).

  • A template view that includes a fragment twice (line 20 and 25) to demonstrate how to reuse code.

  • An XML fragment that demonstrates a simple test (line 10), using expression binding.

Caution

The OData model is based on GWSAMPLE_BASIC and will not work unless a suitable proxy for back-end access is used. For simplicity, no mock data is included in this example.

For more information, see the Help topic, Sample Service - Basic.

1   /*!
2    * ${copyright}
3    */
4 
5   /**
6    * @fileOverview Application component to display supplier of "/ProductSet('HT-1021')"
7    *   from GWSAMPLE_BASIC via XML Templating.
8    * @version @version@
9    */
10  jQuery.sap.declare("sap.ui.core.sample.ViewTemplate.scenario.Component");
11  jQuery.sap.require("sap.ui.model.odata.AnnotationHelper");
12   
13  sap.ui.core.UIComponent.extend("sap.ui.core.sample.ViewTemplate.tiny.Component", {
14      metadata : "json",
15   
16      createContent : function () {
17          var oModel = new sap.ui.model.odata.v2.ODataModel(
18                  "proxy/sap/opu/odata/IWBEP/GWSAMPLE_BASIC/", {
19                  annotationURI : "proxy/sap/opu/odata/IWFND/CATALOGSERVICE;v=2"
20                      + "/Annotations(TechnicalName='ZANNO4SAMPLE_ANNO_MDL',Version='0001')/$value",
21                  json : true,
22                  loadMetadataAsync : true
23              }),
24              oMetaModel = oModel.getMetaModel(),
25              sPath = "/ProductSet('HT-1021')/ToSupplier",
26              oViewContainer = new sap.m.VBox();
27   
28          oMetaModel.loaded().then(function () {
29              var oTemplateView = sap.ui.view({
30                      preprocessors: {
31                          xml: {
32                              bindingContexts: {
33                                  meta: oMetaModel.getMetaContext(sPath)
34                              },
35                              models: {
36                                  meta: oMetaModel
37                              }
38                          }
39                      },
40                      type: sap.ui.core.mvc.ViewType.XML,
41                      viewName: "sap.ui.core.sample.ViewTemplate.tiny.Template"
42                  });
43   
44              oTemplateView.setModel(oModel);
45              oTemplateView.bindElement(sPath);
46              oViewContainer.addItem(oTemplateView);
47          });
48   
49          // Note: synchronously return s.th. here and add content to it later on
50          return oViewContainer;
51      }
52  });
1   <mvc:View
2       xmlns="sap.m"
3       xmlns:core="sap.ui.core"
4       xmlns:form="sap.ui.layout.form"
5       xmlns:mvc="sap.ui.core.mvc"
6       xmlns:template="http://schemas.sap.com/sapui5/extension/sap.ui.core.template/1">
7    
8       <!-- "meta" model's binding context MUST point to an entity type -->
9       <template:with path="meta>com.sap.vocabularies.UI.v1.Badge" var="badge">
10          <form:SimpleForm>
11              <form:title>
12                  <core:Title text="{path: 'badge>HeadLine', formatter: 'sap.ui.model.odata.AnnotationHelper.format'}"/>
13              </form:title>
14   
15              <Label text="{path: 'badge>Title/Label', formatter: 'sap.ui.model.odata.AnnotationHelper.format'}"/>
16              <Text text="{path: 'badge>Title/Value', formatter: 'sap.ui.model.odata.AnnotationHelper.format'}"/>
17   
18              <Label text="{path: 'badge>MainInfo/Label', formatter: 'sap.ui.model.odata.AnnotationHelper.format'}"/>
19              <template:with path="badge>MainInfo" var="field">
20                  <core:Fragment fragmentName="sap.ui.core.sample.ViewTemplate.tiny.Field" type="XML"/>
21              </template:with>
22   
23              <Label text="{path: 'badge>SecondaryInfo/Label', formatter: 'sap.ui.model.odata.AnnotationHelper.format'}"/>
24              <template:with path="badge>SecondaryInfo" var="field">
25                  <core:Fragment fragmentName="sap.ui.core.sample.ViewTemplate.tiny.Field" type="XML"/>
26              </template:with>
27          </form:SimpleForm>
28      </template:with>
29  </mvc:View>
1   <core:FragmentDefinition
2       xmlns="sap.m"
3       xmlns:core="sap.ui.core"
4       xmlns:template="http://schemas.sap.com/sapui5/extension/sap.ui.core.template/1">
5    
6       <!-- "field" MUST point to a com.sap.vocabularies.Communication.v1.DataField -->
7       <HBox>
8           <template:with path="field>Value" helper="sap.ui.model.odata.AnnotationHelper.resolvePath" var="target">
9               <!-- go to entity type's property and check SAP Annotations for OData Version 2.0 -->
10              <template:if test="{= ${target>sap:semantics} === 'tel'}" >
11                  <core:Icon src="sap-icon://phone" width="2em"/>
12              </template:if>
13          </template:with>
14          <Text text="{path: 'field>Value', formatter: 'sap.ui.model.odata.AnnotationHelper.format'}"/>
15      </HBox>
16  </core:FragmentDefinition>

The result is equivalent to the following handwritten XML view. Any references to the meta model are gone. Type information has been inserted into the bindings and an "odata.concat" expression for badge>MainInfo/Value has been processed by sap.ui.model.odata.AnnotationHelper.format, concatenating the company name and legal form.

<mvc:View xmlns="sap.m" xmlns:core="sap.ui.core" xmlns:form="sap.ui.layout.form" xmlns:mvc="sap.ui.core.mvc">
  <form:SimpleForm>
    <form:title>
      <core:Title text="{path : 'BusinessPartnerID', type : 'sap.ui.model.odata.type.String', constraints : {'maxLength':'10','nullable':'false'}}"/>
    </form:title>
    <Label text="Name"/>
    <Text text="{path : 'CompanyName', type : 'sap.ui.model.odata.type.String', constraints : {'maxLength':'80'}} {path : 'LegalForm', type : 'sap.ui.model.odata.type.String', constraints : {'maxLength':'10'}}"/>
    <Label text="Phone"/>
    <HBox>
      <core:Icon src="sap-icon://phone" width="2em"/>
      <Text text="{path : 'PhoneNumber', type : 'sap.ui.model.odata.type.String', constraints : {'maxLength':'30'}}"/>
    </HBox>
    <Label text="Web"/>
    <HBox>
      <Text text="{path : 'WebAddress', type : 'sap.ui.model.odata.type.String', constraints : {}}"/>
    </HBox>
  </form:SimpleForm>
</mvc:View>
Summary
Overall, XML templating is based on:
  • Preprocessing instructions such as <template:if>, which can be used inside XML views

  • An OData meta model which offers a unified access to both, OData v2 metadata and OData v4 annotations

  • A set of OData type implementations which add knowledge of OData types to SAPUI5

  • Expression binding which facilitates the use of expressions instead of custom formatter functions

  • The helper class sap.ui.model.odata.AnnotationHelper that offers formatter and helper functions to be used inside XML template views. It knows about the OData meta model and helps with standard tasks like accessing a label or providing a runtime binding path. It brings in the OData types, along with their facets. Its output uses expression binding, if needed.