如何在dust.js中实现自定义渲染逻辑? [英] How do I implement custom rendering logic in dust.js?

查看:71
本文介绍了如何在dust.js中实现自定义渲染逻辑?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用dust.js来呈现有时长且包含下划线的变量名列表:

I'm using dust.js to render a list of variable names that are sometimes long and contain underscores like:

SUM_COUNT_LABOR_COUNTRIES_SMS_PAST

SUM_COUNT_LABOR_COUNTRIES_SMS_PAST

浏览器不会对下划线进行换行,因此它可能会变得难看。我希望我的灰尘模板在每个下划线后添加零宽度空间,以便浏览器可以包装它。这肯定属于模板层而不是模型,但我无法弄清楚如何使用dust.js正确实现这一点,而且它是将表示与逻辑分离的非常好的原则。

The browser doesn't wrap on underscores so it can get ugly. I'd like my dust template to add a zero-width space after each underscore so the browser can wrap it. This definitely belongs in the template layer and not with the model, but I can't figure out how to properly achieve this with dust.js and it's otherwise very good principle of separating presentation from logic.

我是否创建了助手功能?我在哪里放置辅助功能?
如何从模板中调用它?

Do I create a "helper" function? Where do I put the helper function? How do I call it from the template?

推荐答案

有很多方法可以解决这个问题。我认为你正在寻找的可能是定义一个灰尘过滤器。你可以扩展dust.filters来添加你自己的过滤器。 dust.filters在源代码中看起来像这样:

there are many ways in dust to approach this. what i think you're looking for is to probably define a dust filter. you can extend dust.filters to add your own filter. dust.filters looks like this in the source:

dust.filters = {
  h: function(value) { return dust.escapeHtml(value); },
  j: function(value) { return dust.escapeJs(value); },
  u: encodeURI,
  uc: encodeURIComponent,
  js: function(value) { if (!JSON) { return value; } return JSON.stringify(value); },
  jp: function(value) { if (!JSON) { return value; } return JSON.parse(value); }
};

所以你要做的是为它添加另一个过滤变量的键值。例如如果你使用下划线:

so what you want to do is add another key-value to it that filters your variable. e.g. if you use underscore:

_.extend(dust.filters, {zws: function(value){ your code here}})

然后你可以在你的防尘模板中调用它,如下所示:

then you can call it in your dust template like so:

the variable is: {variable|zws}

希望这会有所帮助。

这篇关于如何在dust.js中实现自定义渲染逻辑?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆