node.js - Dust 模板中的 for 循环

标签 node.js dust.js

我正在使用 NodeJS/Express3 和 dusts-linkedin,我想做的是:

for(var i = locals.first;i < (locals.first + locals.pages); $i++) {
    <div>i</div>
}

我假设我需要创建一个辅助函数,但不清楚如何创建

最佳答案

好的。在我的例子中,我试图创建一个寻呼机,但我将稍微简化一下答案,以便人们可以了解总体思路。可能有更简洁的方法来执行此操作。

我的助手将被称为“寻呼机”。我想传递一些本地变量。这些是 locals.start 和 locals.end - 每个都是代表我的寻呼机开始和结束的数字。我还将传递一个用于寻呼机的 url。

在我的模板中,我调用了助手以及我可能需要的所有参数:

{@pager start="{locals.start}" end="{locals.end}" url="/articles?page=%page%"/}

然后在我的应用程序中添加这个助手。我需要确保我的灰尘模块存在:

cons = require('consolidate'),
dust = require('dustjs-linkedin'),

然后创建助手:

dust.helpers['pager'] = function(chunk, context, bodies, params) {

  //tapping these to get the actual value (since we passed vsaraibles) and casting as a number with '+'
  first = +dust.helpers.tap(params.first, chunk, context);
  last = +dust.helpers.tap(params.last, chunk, context);

  //this one is all ready since we just passed a string
  url = params.url;

  //build our html - do whatever you need here - this is an example
  var html = '<ul>';
  for(var i = first; i <= last; i++) {
    //I used a replace and placeholder - prob other methods you can use
    html += '<li><a href="' + url.replace('%page%', i) + '">' + i '</a></li>';
  }
  html += '</ul>';

  //write this back to the template
  chunk.write(html);

  //return it
  return chunk;
};

希望这对某人有帮助

关于node.js - Dust 模板中的 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12081007/

相关文章:

javascript - 如何获取 fs.rename 的结果

javascript - Dust.js 模板不遵守条件存在

javascript - 如何在 Node 上的 .dust 文件上使用 connect-flash 和 express-messages 显示消息

javascript - Dust.js 在循环中的空值后不添加分隔符

javascript - 使用 Dustjs 遍历对象数组

node.js - Objection.js Stubbing Chained "whereIn"方法与 Sinon

node.js - FCM iOS : Push notifications throw invalid argument

javascript - 无法理解 NodeJS 中的一些基本逻辑

sql - 如何为 Sequelize 转换 SQL 查询?

node.js - 使用 Node uglify + watch 合并目录中的 javascript 文件?