问题
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