+
95
-

请问art-template模板如何自定义函数?

请问art-template模板如何自定义函数?

网友回复

+
15
-

首先要定义一个

  // 百分比计算 自定义模板函数
template.defaults.imports.percentage = function (num1, num2) {if(!num1 && !num1){
       return 0+'%';
    }else{
       return Math.round(num1 / (num1 + num2) * 100) + '%';
    }   
}

然后在模板中调用

 {{ 3,4 | percentage}}

完整示例代码:

<!DOCTYPE html>        
<html lang="en">        
<head>        
    <meta charset="UTF-8">        
    <title>超快的模板引擎 art-template.js</title>      
    <style type="text/css">  
    </style>       
</head>        
<body>  
  <div id="content"></div>
  
  <script id="test" type="text/html">
    <h1>{{title}}</h1>
    <ul>
        {{each list as value i}}
            <li>索引 {{i + 1}}:{{value}}  {{i + 1,1 | percentage}} </li>
        {{/each}}
    </ul>
  </script>
<script type="text/javascript" src="//repo.bfw.wiki/bfwrepo/js/art-template.js"></script>
<script type="text/javascript" src="//repo.bfw.wiki/bfwrepo/js/jquery-3.2.1.min.js"></script>
  <script type="text/javascript"> 
  // 百分比计算 自定义模板函数
template.defaults.imports.percentage = function (num1, num2) {if(!num1 && !num1){
       ret...

点击查看剩余70%

我知道答案,我要回答