[英]html template in jquery or javascript
This is a very short example, but I was wondering if there is a way of using an xml or html file with html markup instead of including it in the javascript like I do below. 这是一个非常简短的示例,但我想知道是否有一种方法可以使用带有html标记的xml或html文件,而不是像我下面所做的那样将其包含在javascript中。
I know there are template libraries out there, but I really just want to do something simple and not involve any libraries other than jQuery. 我知道那里有模板库,但是我真的只想做一些简单的事情,并且不涉及jQuery以外的任何库。
var description = this.name;
if description == 'full') {
return "<div><textarea cols='50' rows='50'>" + this.value + "</textarea></div>";
} else {
return "<div><textarea cols='50' rows='15'>" + this.value + "</textarea></div>";
};
Thanks 谢谢
In general, without a template engine you have three options: 通常,没有模板引擎,您有三个选择:
a) Adding the template directly into your markup as script tag a)将模板作为脚本标签直接添加到您的标记中
<script type="text/template" data-template="stats">
<div id="content">
...
</div>
</script>
The html code inside the script tag could be accessed with the following code: 可以使用以下代码访问script标记内的html代码:
$("script[data-template=" + templateName + "]").html()
The big benefit of this approach is that you are not making another http request. 这种方法的最大好处是您不会发出另一个http请求。
b) Putting the template in external file and load it via ajax. b)将模板放入外部文件,并通过ajax加载它。
$.ajax({
url: "test.html"
}).done(function(html) {
...
});
c) Doing the things like you already did. c)做像您已经做的事情。
如果使用AJAX调用文件,则可以使用文件的结果,该结果可以是XML或嵌套的HTML等。
I define a hidden div on my markup - then give it a generic ID, then in javascript I use the jQuery.clone() method to make a clone of that markup, and in the markup I define the template macro values that can then be injected with the real data using .replace.. 我在标记上定义了一个隐藏的div-然后给它一个通用ID,然后在javascript中使用jQuery.clone()方法对该标记进行克隆,然后在标记中定义模板宏值,然后可以使用.replace ..注入真实数据
HTML: HTML:
<div id="mytemplate">
Name: {0}
</div>
JS/jQuery: JS / jQuery的:
var clone = $('#mytemplate').clone();
Then perform the replacements on the clone object and simply append to the DOM where desired! 然后在克隆对象上执行替换操作,并在需要的地方简单地附加到DOM!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.