简体   繁体   English

JSRender内联模板

[英]JSRender inline templates

Using JSRender it's possible to create templates using script tags that are of type "text/x-jsrender". 使用JSRender可以使用类型为“ text / x-jsrender”的脚本标签创建模板。 Eg 例如

<script id="movieTemplate" type="text/x-jsrender">
        <li>
            {{>name}} {{>releaseYear}}
        </li>
</script>

It can then be rendered as follows: 然后可以将其呈现如下:

<script type="text/javascript">
        $("#movieList").html(
            $("#movieTemplate").render(movies)
        );
</script>

However for simple templates I'd prefer to declare them inline rather than in a separate "text/x-jsrender" script tag. 但是对于简单的模板,我宁愿以内联方式声明它们,而不是在单独的“ text / x-jsrender”脚本标记中声明。 Is this possible? 这可能吗? I was thinking something along the lines of: 我在考虑以下方面:

   var myTemplate = "<li>{{>name}} {{>releaseYear}}</li>";
   var outputHtml = render(myTemplate, movies);

You can do this using $.templates() . 您可以使用$.templates()进行此操作。 You're close you're just missing one line: 关闭,您只缺少一行:

var myTemplateText = "<li>{{>name}} {{>releaseYear}}</li>";
var myTemplate = $.templates(myTemplateText);
var outputHtml = myTemplate.render(movies);

As a note though, one of the benefits of templates is you can separate your presentation from your code. 值得注意的是,模板的优点之一是您可以将演示文稿与代码分开。 Meaning if I'm a designer, I can easily mess with your template HTML without needing to know the JavaScript logic. 这意味着如果我是设计师,则可以轻松理解您的模板HTML,而无需了解JavaScript逻辑。 When you do it the way I show above, you lose that ability since you've mixed presentation and logic. 当您按照我上面的方法进行操作时,由于混合了演示文稿和逻辑,您将失去这种能力。 It's up to you whether you're OK with that or not. 是否可以接受,取决于您自己。

In any case there are some good examples of different ways to create templates on the JSRender website . 无论如何,在JSRender网站上都有一些很好的示例,介绍了不同的方法来创建模板。

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

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