javascript - Mustache/jQuery/javascript - 如何对 mustache 变量执行方法?

标签 javascript jquery mustache

我有一个简单的 mustache 模板设置,它采用一个对象 player 并创建一个列表元素。对 mustache 中的变量执行 javascript 方法的最佳方法是什么?下面是一些示例代码:

var playerTemplate = '<li><span class="player-position">{{ position }}</span><span class="player-name">{{ first_name }} {{ last_name }}</span></li>';
var playerRow = Mustache.to_html(playerTemplate, player);
$('ul#players-list').append(playerRow);

我想做的是:

{{ position.toUpperCase() }}

我宁愿不更改对象本身,因为我可能希望 {{ position }} 在其他情况下不为大写。有没有关于最干净、最聪明的方法的提示?

非常感谢。

最佳答案

Mustache 有意设计得非常简单(“无逻辑模板”),因此您无能为力。一种选择是添加 positionUC 属性:

player.positionUC = player.position.toUpperCase();

然后在模板中:

{{positionUC}}

你还可以添加函数:

// Note that render(text) will be HTML though...
player.uc = function(text, render) { return render(text).toUpperCase() };

然后在模板中:

{{#uc}}{{position}}{{/uc}}

也许你可以切换到 Handlebars并为大写字母添加一个助手。

关于javascript - Mustache/jQuery/javascript - 如何对 mustache 变量执行方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8460720/

相关文章:

php - 将文件夹内容中的单个 img src 读取为 HTML

Javascript 小部件(类似于 Facebook Like)脚本 vs Iframe 方法

javascript - 从下到上取消隐藏div

JQuery - 检测 div 内任意位置的点击(包括其他元素)

javascript - 当字段为空时如何省略一行(使用 mustache / Handlebars )

javascript - 两个全宽 div 之间的 slider

javascript - Google 表格 - 根据条件发送电子邮件

javascript - 获取链接 url 的特定部分

spring-boot - Spring Boot 看不到 mustache 模板

javascript - mustache.js 中的 switch 语句