简体   繁体   English

Handlebars模板,使用字符串键访问上下文变量

[英]Handlebars templates, access context variables with a string key

Let's say I have a handlebars template like this: 假设我有一个像这样的把手模板:

      <script id="entry-template" type="text/x-handlebars-template">
       <div class="entry">
          <h1>{{i18n.title}}</h1>
       </div>
      </script>

What I really would like to do is something like this: 我真正想做的是这样的事情:

var source   = $("#entry-template").html();
var template = Handlebars.compile(source);
var context = {"title.t":"My New Post"}
console.log(template(context));

When I try to parse in a context like above with a string as the key, hanslebars acts like the key is not available. 当我尝试使用字符串作为键来解析上面的上下文时,hanslebars就像密钥不可用一样。 I do understand that normaly the structure should be like this: 我明白,结构应该是这样的:

var context = {
    i18n:{
      title:'test'
    }
}

But because I'll get my 118n strings from an external source, it would be easier to just use them as keys. 但是因为我将从外部源获取我的118n字符串,所以将它们用作键是更容易的。 Ah and yes, I know projects like i18n.js, but the actual question is: Can I use a string-key in the context object with dots in it and if yes, how can I access them from the handlebars template? 啊,是的,我知道像i18n.js这样的项目,但实际的问题是:我可以在上下文对象中使用带有点的字符串键,如果是,我如何从把手模板中访问它们?

Old question, but I still want to post what I've found out. 老问题,但我仍想发布我发现的内容。

If the key to your key:value pair is represented as a string, you could place the string itself in your handlebars template placeholder. 如果key:value对的键表示为字符串,则可以将字符串本身放在handlebars模板占位符中。

So if your context is: 因此,如果您的上下文是:

var context = {
    "key":"value"
}

As opposed to this: 与此相反:

var context = {
    key: "value"
}

You could do this in your template to show the value: 您可以在模板中执行此操作以显示值:

<p>{{"key"}}</p>

So, handlebars will treat it as a property name, and display the value. 因此,把手会将其视为属性名称,并显示该值。

Example: 例:

var names = {
    "first": "John",
    "last": "Doe"
}
<script id="names-template" type="text/x-handlebars-template">
<p>First Name: {{"first"}}</p>
</script>

Will output: 将输出:

First Name: John 名字:约翰

This respects spaces and other characters in your key strings, we tested it, and it works with dots within your strings too. 这尊重你的关键字符串中的空格和其他字符,我们对它进行了测试,它也适用于字符串中的点。 Give it a try and let me know. 试一试,让我知道。

No you cannot use keys with dots in them. 不,你不能使用带点的键。 This is because they are part of the syntax. 这是因为它们是语法的一部分。 If you could use dots then how would you access children of that element? 如果你可以使用点,那么你将如何访问该元素的子元素? Instead of dots, use underscore or dash. 而不是点,使用下划线或短划线。 It's a standard people respect because it doesn't introduce bugs and other weird behaviour. 这是一个标准的人尊重,因为它不会引入错误和其他奇怪的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM