使用 Mustache.js 转义变量名

Escape variable name with Mustache.js

我有一个要解析到 JSON 然后发送到 Mustache.js 的 csv 文件。问题是一些变量名格式不正确,所以我最终得到的对象可能如下所示:

{
    'Num.': '1234',
    'Pass-through': 'yes'
}

那么我该如何在 Mustache 模板中使用这些变量呢?我尝试了几种不同的方法。

<td>{{ Num. }}</td>
<td>{{ 'Num.' }}</td>
<td>{{ ['Num.'] }}</td>

但其中 none 个有效(如果有效我会更惊讶),并且在文档中找不到任何关于如何转义变量名的内容。

手动

overview: | Interpolation tags are used to integrate dynamic content into the template.

The tag's content MUST be a non-whitespace character sequence NOT containing the current closing delimiter.

This tag's content names the data to replace the tag. A single period (.) indicates that the item currently sitting atop the context stack should be used; otherwise, name resolution is as follows:

  1. Split the name on periods; the first part is the name to resolve, any remaining parts should be retained.
  2. Walk the context stack from top to bottom, finding the first context that is a) a hash containing the name as a key OR b) an object responding to a method with the given name.
  3. If the context is a hash, the data is the value associated with the name.
  4. If the context is an object, the data is the value returned by the method with the given name.
  5. If any name parts were retained in step 1, each should be resolved against a context stack containing only the result from the former resolution. If any part fails resolution, the result should be considered falsey, and should interpolate as the empty string.

Data should be coerced into a string (and escaped, if appropriate) before interpolation.

简而言之:您不能拥有名称为 'Num.'.

的元素

默认情况下,所有变量都HTML转义。如果你想 return 未转义 HTML,请使用三胡子:{{{name}}}。 如果这不起作用,您可以使用一个简单的函数 returns 它是未转义的输入。