如何使用dustjs-linkedin作为客户端模板?

pay*_*ike 9 node.js client-side-templating dust.js

我得到了服务器和客户端模板的想法,但是dust.js让我感到困惑.

为了将dust.js用于客户端模板,您需要三个步骤:

  1. 编译模板
  2. 加载模板
  3. 渲染模板

对?

但模板来自哪里?我看到了两种不同的方法:

 1. <script> template <script>
 2. <div> template </div>
Run Code Online (Sandbox Code Playgroud)

......他们都在DOM中.哪个是对的?

我还注意到你可以通过ajax加载模板,所以模板不会在DOM中看到,但我不知道如何做到这一点.

另外,我目前正在使用jade作为快速查看引擎.是否有必要切换到dust.js?有什么好处?

Omi*_*deh 12

这是LinkedIn Dust JS维基页面,可以回答您的问题,并有很好的例子:http://linkedin.github.com/dustjs/

但是在这里回答你的问题:

是的,您需要编译您的灰尘模板,该模板将成为可以按<script>标签添加到页面的JavaScript文件,然后调用dust.render方法来呈现模板.这是一个例子:

  1. 在模板文件中编写以下代码并将其另存为sample.tl

    <p>Hi {firstName} {lastName}</p>
    
    Run Code Online (Sandbox Code Playgroud)
  2. 通过dustc sample.tl命令行将sample.tl编译为sample.js 或者用于dust.compile("your_template_code", "template_name")编译模板并将输出保存在JavaScript文件(sample.js)中,或者使用duster.js通过nodejs监视和编译模板:https:// github的.com/DMIX/dusterjs

  3. 在你的html中添加sample.js:

    <script type="text/javascript" src="sample.js"></script>
    
    Run Code Online (Sandbox Code Playgroud)

    这也会将你的模板注册到dust.cache.

  4. 在你的JavaScript中:

    var your_json = {firstName:'James', lastName:'Smith'};
    
    dust.render('sample', your_json, function(err, out){
    
        your_dom_element.innerHTML = out;
    
    });
    
    Run Code Online (Sandbox Code Playgroud)

    上述dust.render方法的结果将是<p>Hi James Smith</p>

    所以你需要传递3个参数dust.render:dust.render(template_name, json, callback)