WeChat Mini Program Template
Template
WXML provides a template (Template), in which code snippets can be defined and then used in different places. The format and data can be guaranteed to be the same.
1-Define the template
Use the `` tag to define the template, name the template name tempName, and assign the value to the attribute name . Inside the tag, define the template structure. As follows:
<!-- template.wxml --> <!-- index: int msg: string time: string --> <template name="msgItem"> <view> <text> {{index}}: {{msg}} </text> <text> Time: {{time}} </text> </view> </template>
2-Use template
Use the tag where you need to use a template. If you want to use the data in the js file, you need to add the data attribute. As follows:
<!-- template.wxml --> <template is="msgItem" data="{{...item}}"/> <template is="msgItem" data="{{...item}}"/> <template is="msgItem" data="{{...item}}"/> 此时在页面上就会重复显示三次相同的信息。 data中的数据,来源于js文件,如下: <!-- template.js --> Page({ data: { item: { index: 0, msg: 'this is a template', time: '2016-09-15' } } })
3-is attribute
The is attribute can not only statically point to the rendered template, but also use Mustache syntax to dynamically determine which template needs to be rendered. . As follows:
<!-- template.wxml --> // templates <template name="odd"> <view> odd </view> </template> <template name="odd"> <view> even </view> </template> // is属性使用Mustache语法动态渲染template <block wx:for="{{[1, 2, 3, 4,5]}}"> <template is="{{item % 2 == 0 ? 'even' : 'odd'}}" /> </block>
The above code will display odd or even on the page according to the conditions
4-Template reference
Both of the above The template is defined and referenced in the same wxml file, and the definition and reference of the template can be separated. That is, the template is defined in one file, and the defined template can be used in one or more other wxml files.
To reference a template from an external file, use the import src="templateUrl" /> tag. Also use the is attribute to point to the tag to be referenced.
For example, the directory is as follows:
-pages |--index |--index.js |--index.json |--index.wxml |--index.wxss |--template |--template.js |--template.json |--template.wxml |--template.wxss
To use the template defined in template in index.wxml, you need to import the template in index first:
<!-- index.wxml --> <import src="../template/template.wxml" <template is="msgItem" data={{...indexData}} // 使用的是自己js文件中的数据
Pay attention to the import scope, which only refers to the template in the target file. For example: C import B, B import A, the template defined by B can be used in C, and the template defined by A can be used in B, but C cannot use the template defined by A.
Thank you for reading, I hope it can help you, thank you for your support of this site!
For more detailed explanations of WeChat Mini Program Template and simple examples, please pay attention to the PHP Chinese website!