`

jquery template plugin介绍

 
阅读更多

   由上文看,模版替换的确可以很大程度降低拼接html带来的麻烦,然而在用法上还是比较麻烦一点,鉴于现在大多数前端js框架都是以jquery为基础的,那么现在我推荐一个更为简单的解决方案——jquery template plugin。对它作为jquery的一个插件,在很大程度上可以降低使用复杂度。但在功能上没有jstemplate强大。

 

   1.首先下载库文件  下载


     如图,templates.js就是该插件,min.js为压缩后的文件。

 

   2.插件的使用方法

 

$( selector ).render( values, options ); 

selector: jquery选择器,指定某个dom要进行渲染

values: {key:value}替换的数据,也可以是一个{key:value}数组

options:
{
  clone: (true|false) 如果是true,复制一个新的html片段,而非直接替换. Defaults to false.
  preserve_template: 缺省的模版渲染后,模版将会被填充重写,并且无法被二次使用.
      preserve_template:true 保持该模版在html中. 
    
  beforeUpdate:模版渲染前触发
           function( new_node ) {}  //new_node即为渲染出的节点,可以通过jQuery(new_node)将其转化为jquery对象
  afterUpdate: 模版渲染后触发
            function( new_node ) {}
}
 

      3.具体例子

  • 简单替换
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" >
	<head>
		<title>Template Tests</title>
		<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js" ></script>
		<script type="text/javascript" src="http://jquery-templates-plugin.googlecode.com/files/templates-1.1.1.min.js" ></script>
		<script type="text/javascript" >

		$(document).ready( function()
		{

			  $('#hello_world').render( {
					'token0': 'hello_world',
					'token1': 'hello',
					'token2': 'world'
				});

		});

		</script>
	</head>
	<body>
		<div id="hello_world" class="{token0}" >
			Great programmers begin with: {token1}, <span>{token2}</span>
		</div>
	</body>
</html>
 

执行结果:

 

Great programmers begin with: hello, world
  •  选择器多个目标模版
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" >
	<head>
		<title>Template Tests</title>
		<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js" ></script>
		<script type="text/javascript" src="http://jquery-templates-plugin.googlecode.com/files/templates-1.1.1.min.js" ></script>
		<script type="text/javascript" >

		$(document).ready( function()
		{

			  $('.hello_world').render([
					{'token0': 'hello','token1': 'world'},
					{'token0': 'foo','token1': 'bar'}
				]);

		});

		</script>
	</head>
	<body>
		<div class="hello_world" >
			Great programmers begin with: {token0}, <span>{token1}</span>
		</div>
		<div class="hello_world" >
			Other great programmers begin with: {token0}, <span>{token1}</span>
		</div>

	</body>
</html>
 由于$("hello_world")有两个片段,故传入参数为一个数组。渲染结果
Great programmers begin with: hello, world
Other great programmers begin with: foo, bar
如果,只传入一组值,如

 

 $('.mytemplate').render(  {
    'token0': 'hello', 'token1': 'world',
  });

// $('.mytemplate').render(  [{
//    'token0': 'hello', 'token1': 'world',
//  }]);

 则,所有模版均用相同值渲染即结果均为:

 

Great programmers begin with: hello, world
Other great programmers begin with: hello, world

 

 如果模版多余传入值数组,则后面的模版值均被渲染成最后一个数组元素的值。

  •  嵌套结构数据
  比较简单,直接看例子
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" >
	<head>
		<title>Template Tests</title>
		<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js" ></script>
		<script type="text/javascript" src="http://jquery-templates-plugin.googlecode.com/files/templates-1.1.1.min.js" ></script>
		<script type="text/javascript" >

			$(document).ready( function () 
			{

				$('#lotr').render( {

					'halflings' : [ 
						{'name': 'frodo', 'armor':'mithril'},
						{'name': 'sam',   'armor': 'cloth' } 
					] 
	 
				});

			});

		</script>
	</head>
	<body>
		<div id="lotr" >
			<ul>
				<li>{halflings.0.name} has {halflings.0.armor} armor</li> //索引方式引用
				<li>{halflings.1.name} has {halflings.1.armor} armor</li> 
			</ul>	
		</div>
	</body>
</html>
 渲染结果:

  • frodo has mithril armor
  • sam has cloth armor
  •   选择器替换
       可以限定只有和指定选择器匹配的模版标签才可参与渲染。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" >
	<head>
		<title>Template Tests</title>
		<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js" ></script>
		<script type="text/javascript" src="http://jquery-templates-plugin.googlecode.com/files/templates-1.1.1.min.js" ></script>
		<script type="text/javascript" >

			$(document).ready( function () 
			{

				$('#mytemplate').render( { 
					'$("span, strong, p")': { dog_sound: 'woof', pig_sound: 'oink' } 
				});

			});

		</script>
	</head>
	<body>
		<div id="mytemplate" >
			Dogs say <span>...{dog_sound}</span>, <strong>...{dog_sound}</strong>
			<p>But pigs say {pig_sound}!!!</p>
			But you should see these tokens: {dog_sound}, {pig_sound} because they don't match the selector.
		</div>
	</body>
</html>
 
  渲染结果:
Dogs say ...woof, ...woof
But pigs say oink!!!

But you should see these tokens: {dog_sound}, {pig_sound} because they don't match the selector.
  • clone
    刚才看见了多个模版,一条数据的情况,但实际代码里,往往模版是一个,而会有很多不同的数据依赖同一个模版生成,如何完成此需求呢,我们使用clone。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" >
	<head>
		<title>Template Tests</title>
		<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js" ></script>
		<script type="text/javascript" src="http://jquery-templates-plugin.googlecode.com/files/templates-1.1.1.min.js" ></script>
		<script type="text/javascript" >

			$(document).ready( function () 
			{

				$('#clone_me').render(
				[
					{ 
						'rendered_class': 'rendered',
						'query_param'   : 'x',
						'your_value'    : 'clone1' 
					},
					{ 
						'rendered_class': 'rendered',
						'query_param'   : 'y',
						'your_value'    : 'clone2' 
					}

				], {clone:true} );

			});

		</script>
	</head>
	<body>

		<ul>
			<li id="clone_me" class="template {rendered_class}" ><a href="?q={query_param}" >The clone is: {your_value}</a></li>
		</ul>
	
	</body>
</html>
 渲染结果:
  这时大家要问,如果我只是某一块需要模版重复生成,而其它又不需要clone,怎么办,这里plugin提供了一个新的语法 @(selector),这样他就仅对此部分进行clone,例:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" >
	<head>
		<title>Template Tests</title>
		<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js" ></script>
		<script type="text/javascript" src="http://jquery-templates-plugin.googlecode.com/files/templates-1.1.1.min.js" ></script>
		<script type="text/javascript" >

			$(document).ready( function () 
			{

				$('#lotr').render( {

					'who_says': 'Aragorn',

					'@("li.halfling_tmpl")' : [ 
						{'name': 'frodo',    'armor': 'mithril'},
						{'name': 'sam',      'armor': 'cloth' }, 
						{'name': 'pippin',   'armor': 'accidental' } 
					] 
	 
				}, {clone: true} );

			});

		</script>
	</head>
	<body>
		<div id="lotr" >
			{who_says}'s Famous Quotes:
			<ul>
				<li class="halfling_tmpl">{name} has {armor} armor</li> 
			</ul>	
		</div>
	</body>
</html>
 渲染结果:
Aragorn's Famous Quotes:
  • frodo has mithril armor
  • sam has cloth armor
  • pippin has accidental armor
 

参考:http://ivorycity.com/blog/jquery-template-plugin/

  • 大小: 5.5 KB
分享到:
评论

相关推荐

    jquery-template-plugin:一个简单的jQuery插件,它使用模板和传递的json对象生成动态html内容

    jQuery模板 一个简单的jQuery插件,它使用模板和传递的json对象生成动态html内容。 执照 版权所有(c)2012 Kapil Kashyap。 在MIT许可和GPL许可下获得双重许可。

    jquery-plugin-template

    jQuery 插件模板使用您需要的所有文件立即启动您的 jQuery 插件。 它提供了一个咕噜声的设置: QUnit 测试包括: 代码覆盖毯子sinon 用于模拟和伪造 AJAX 调用测试将使用 PhantomJS 在无头浏览器中运行jshint 代码...

    jQuery-Plugin-Template:结合Lightweight Start模式,参考Bootstrap写出的jQuery模板

    jQuery-Plugin-Template 结合Lightweight Start模式,参考Bootstrap写出的jQuery模板 调用方法 使用template.js文件 使用默认参数进行初始化 $('p').myplugin();//init() 传入对象进行初始化 $('p').myplugin({ key...

    jquery.plugin-boilerplate:简单而固执的jquery插件样板

    jquery.plugin-样板 简单而固执的jquery插件样板。 以下是此样板的完整指南。 先决条件 jQuery的。 // required plugins. &lt; script src = "https://code.jquery.com/jquery-3.4.1.min.js" &gt; &lt; / script &gt; ...

    jquery-plugin-template:用于创建jQuery插件的模板。 基于jQuery-boilerplate,内置测试开始

    jQuery插件模板 一个基于jQuery插件模板和George Paterson的的测试配置。 用法 包括jQuery: &lt; script src =" http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js " &gt; &lt;/ script &gt; ...

    jQuery-Plugin-Template:具有初始化,重置和销毁方法的jQUery插件模板

    jQuery插件模板 带有初始化,重置和销毁方法的jQuery插件模板。

    jquery-plugin-list:创建列表jQuery插件

    html-web-template 简单HTML,CSS,JS Web项目结构模板

    jquery.keyboard:jQuery键盘插件

    当前版本0.0.1演示版在浏览器template / index.html上运行缩小的特征快速开始### 3简单步骤链接到jquery.virtual_plugin.css &lt;link href="assets/plugin/jquery.virtual_plugin/jquery.virtual_plugin.css" rel=...

    JavaScript模板引擎Mustache.zip

    基于javascript 实现的模板引擎,类似于 Microsoft’s jQuery template plugin,但更简单易用! 标签:Mustache

    Wrox.Professional.jQuery 2012

    Chapter 11 focuses on the jQuery Template plugin. Templates are a standard way of marrying data and markup snippets. Chapter 12 focuses on authoring jQuery plugins. It is important to know how to ...

    jQuery File Upload

    •Using the plugin with jQuery UI. •How to submit additional Form Data. •How to submit files asynchronously. •Upload multiple resolutions of one image with multiple resize options •Multiple File ...

    WordPress 3 Plugin Development Essentials.pdf

    Adding a button template 57 Getting the post URL 58 In your browser—getting the post URL 60 Getting the post title 60 Getting the description 60 Getting the media type 62 Getting the post topic...

    常用的JavaScript模板引擎介绍

    基于javascript 实现的模板引擎,类似于 Microsoft’s jQuery template plugin,但更简单易用! 2. doT.js doT.js 包含为浏览器和Node.js 准备的 JavaScript 模板引擎。 3. jSmart jSmart 是著名的 PHP 模板引擎 Smarty...

    jquery-smartwizard:很棒的jQuery步骤向导插件

    jQuery Smart Wizard v5 很棒的jQuery步骤向导插件。 jQuery Smart Wizard是jQuery的可访问步骤向导插件。 为您的表单,结帐屏幕,注册步骤等提供简洁时尚的界面。易于实现,Bootstrap兼容性,可自定义的工具栏,...

    jQuery完全实例.rar

    You can pass in plain HTML Strings written by hand, create them using some template engine or plugin, or load them via AJAX. There are limitations when creating input elements, see the second example....

    jQuery1.2API

    You can pass in plain HTML Strings written by hand, create them using some template engine or plugin, or load them via AJAX. There are limitations when creating input elements, see the second example....

    voi-plugin:voi jquery 插件

    语音插件voi jquery 插件需要jQuery 下载并在 jquery 之后包含此插件。 如果您还没有,请在发起一场辩论。 将您的链接(请参阅下面的网址)放在此输入框中以供参考。 该插件将访问voteoverit.com 系统并返回一个具有...

    Knockoutjs入门实用资源(经典)

    在JavaScript領域,過去也有些MVVM程式庫被提出來,例如: 微軟主導的jQuery Data Link Plugin(不過,它跟jQuery Template Plugin一樣,已停止發展,未來會由jsView及jsRender接替,但預估要到2012年中才會進入Beta階...

    WordPress 2.8 Theme Design.pdf

    Adding sIFR text with the jQuery Flash plugin 233 Flash in a WordPress post or page 236 Adding You Tube video to a WordPress post 236 Summary 238 Chapter 9: Design Tips for Working with WordPress ...

    bootstrap ace_admin1.3.1 (最新版)

    Nestable lists plugin typeahead.js Dual listbox Multiselect jQuery raty The following is on to-do list and will be added to Ace in next updates: New features & elements such as : Wysiwyg editor (now...

Global site tag (gtag.js) - Google Analytics