How to change JsRender template tags?

隐身守侯 提交于 2019-12-04 04:33:58

问题


I use Twig. It uses these tags: {{ name }}

I want to include JsRender in my project. But JsRender also uses the same tags {{:name}}, so there is a conflict and nothing works. How to change default JsRender tags with custom tags, say Ruby-like <%= name %>

UPD:

For some reason I cannot make it work with control flow tags, for doesn't behave as expected with custom tags. Why does it happen?

Here is a template:

<script id="myTmpl" type="text/x-jsrender">
    <%!-- This is a copmment %>
    <% for data %>
        <%:key%>
    <% /for %>
</script>

Here is js code:

var template = $.templates("#myTmpl");
var htmlOutput = template.render(data);
$(".div").html(htmlOutput);

Here is a rendered result:

<%!-- This is a copmment %> <% for data %> <% /for %>

回答1:


JsRender let's you change the delimiters, like this:

$.views.settings.delimiters("<%", "%>");

So then you would write <%: name %>.

If you use JsViews, you can also set the binding character ^ in {^{ - by writing:

$.views.settings.delimiters("<%", "%>", "*");

then using <*%: name %>.

Example (runs as snippet below):

<%!-- a comment --%>

<%:title%>
<%for items%>
    <div><%:name %></div>
<%/for%>

$.views.settings.delimiters("<%", "%>");

var data = {
  title:"The Title",
  items: [
	{name:"Item one"},
		{name:"Item two"}
	]
};

var template = $.templates("#myTmpl");

var htmlOutput = template.render(data);

$("#result").html(htmlOutput);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//www.jsviews.com/download/jsrender.js"></script>

<script id="myTmpl" type="text/x-jsrender">
<%!-- a comment --%>
<%:title%>
<%for items%>
	<div><%:name %></div>
<%/for%>
</script>

<div id="result"></div>

Note that you must simply replace the original "{{" and "}}"characters by the chosen replacement ones, but not change the whitespace. After replacement, <% for items%> would be incorrect, since the correct syntax is {{for items}}, not {{ for items}}. (That was your error above...). It should be <%for items%>. etc.

See Setting tag delimiters for JsRender for documentation.

See http://www.jsviews.com/#jsrtags for tag syntax.



来源:https://stackoverflow.com/questions/29493005/how-to-change-jsrender-template-tags

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!