artTemplate模版引擎的簡潔語法的基本用法

不落不息發表於2020-10-05

artTemplate開源社群
中文說明文件

基本引用和迴圈

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>引擎模版使用</title>
	<script type="text/javascript" src="template.js"></script>
 	<script type="text/javascript">
		window.onload = function(){
		    var data ={
			    title : '小孩資訊',
			    stu : ["小紅",'小星','無名','媛媛']
		    }

		    //引數1:下面的id名
		    //引數2:需要渲染的資料
		    //結果:生成靜態的頁面片段
		    var html = template('templt',data);
		    document.getElementById("box").innerHTML =html;
	    }
	</script> 
	<script type="text/html" id="templt">
		<!-- type格式: text/html ; id名自取 -->
		<!-- {{varName}} :中存放資料 -->

		<h1>{{title}}</h1>  
		<!-- 迴圈判斷:判斷stu是否存在
			使用each迴圈
		 -->
		{{if stu}}
		    {{each stu as value i}}
		        <div>{{value}}</div>
		    {{/each}}
		{{/if}}
	</script>
</head>
<body>
	<div id="box"></div>
</body>
</html>

示例程式碼(轉義與不轉義)

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>引擎模版使用</title>
	<script type="text/javascript" src="template.js"></script>
</head>
<body>
	<div id="content"></div>
	<script id="test" type="text/html">
		{{if isAdmin}}
		     <h1>{{title}}</h1>
		     <ul>
		     	{{each list as value i}}
		     	<li>索引 {{i + 1}} : {{value}}</li>
		     	{{/each}}
		     </ul>
		{{/if}}

		<p>不轉義:{{#strs}}</p>
		<p>預設轉義:{{strs}}</p>
	</script>
	<script>
		// isAdmin:更加靈活,可以根據使用者身份來看是否可以獲取當前許可權
		var data ={
			title:'基本例子',
			isAdmin:true,
			list:["文藝","攝影","部落格","電影"]
		}
		var html = template('test',data);

		var desc = {
			strs: "<span style='color:#F00'>hello world!</span>"
		}
		document.getElementById("content").innerHTML =html+template('test',desc);
	</script>
</body>
</html>

在js中存入模版

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>引擎模版使用</title>
	<script type="text/javascript" src="template.js"></script>
</head>
<body>
	<h1>在JavaScript中存放模版</h1>
	<div id="content"></div>
	<script>
		var source = '<ul>'
		+            '{{each list as value i}}'
		+            '<li>索引 {{i + 1}} :{{value}}</li>'
		+            '{{/each}}'
		+            '</ul>';

		//compile : 用模版生成新的函式
		//render :渲染傳入的引數,然後輸出靜態標籤內容
		var render = template.compile(source);
		var html =render({
			list:["文藝","攝影","部落格","電影"]
		});
		document.getElementById("content").innerHTML =html;
	</script>
</body>
</html>

嵌入子模板

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>引擎模版使用</title>
	<script type="text/javascript" src="template.js"></script>
</head>
<body>
	<div id="content"></div>
	<script id="test" type="text/html">
		<h1>{{title}}</h1> {{include 'child'}}
	</script>

	<script type="text/html" id="child">
		<ul>
			{{each list as value i}}
			<li>索引 {{i + 1}} : {{value}}</li>
			{{/each}}
		</ul>
	</script>
	<script>
		var data = {
			title: '嵌入子模板',
			list:["文藝","攝影","部落格","電影"]
		}
		document.getElementById("content").innerHTML = template('test',data);
	</script>
</body>
</html>

相關文章