`

jQuery.View - Client Side Templates for jQuery

阅读更多

Everyone loves client side templates. They are a great way to create html which is something JavaScript apps do all the time.

In February, a jQuery templating system was proposed and resulted in a tremendous amount of discussion , followed by an official templating engine for jQuery - jquery-tmpl .

Although jquery-tmpl is a solid templating engine, the discussion highlighted three extremely important facts about developers and client side templates:

Fact 1: Everyone has their own favorite templating engine.

There's a whole slew of templating languages people like:

Most of these template engines have distinct advantages and dissadvantages. It's impossible to expect a single template engine to meet everyone's needs.

Fact 2: Most templating engines provide the exact same features.

I've yet to encounter a template that does't provide:

  • A way of loading templates (typically from HTMLElement or files)
  • A way of caching processed templates.
  • An interface to render the template with arbitrary data.

Fact 3: Very few people are familiar with the complexities of using templates.

There's more than just syntax and magic tag preference that goes into a templating system. Consider:

  • How can I build and share plugins that uses templates?
  • How can I share templates across pages / apps?
  • How can I organize template files?

jQuery.View

jQuery.View is a templating interface that takes care of the complexities of using templates, while being completely template agnostic.

This means that you can use any templating language in the exact same way and get all the additional features that jQuery.View provides.

Features

  • Convenient syntax.
  • Template loading from html elements and external files .
  • Synchronous and asynchronous template loading.
  • Template preloading.
  • Caching of processed templates.
  • Bundling of processed templates in production builds.

Downloads

Documentation

JavaScriptMVC's View Docs .

Use

When using views, you're almost always wanting to insert the results of a rendered template into the page. jQuery.View overwrites the jQuery modifiers so using a view is as easy as:

$("#foo
").html
('mytemplate.ejs
',{message: 'hello world'

}

)

This code:

  1. Loads the template a 'mytemplate.ejs'. It might look like:

    <h2
    >
    <%= message %>
    </h2
    >
    
    
  2. Renders it with {message: 'hello world'}, resulting in:

    "<h2
    >
    hello world</h2
    >
    "
    
  3. Inserts the result into the foo element. Foo might look like:

    <div
     id='foo'
    
    >
    <h2
    >
    hello world</h2
    >
    </div
    >
    
    

jQuery Modifiers

You can use a template with the following jQuery modifier methods:

after $('#bar').after('temp.jaml',{});
append $('#bar').append('temp.jaml',{});
before $('#bar').before('temp.jaml',{});
html $('#bar').html('temp.jaml',{});
prepend $('#bar').prepend('temp.jaml',{});
replace $('#bar').replace('temp.jaml',{});
replaceWidth $('#bar').replaceWidth('temp.jaml',{});
text $('#bar').text('temp.jaml',{});

Template Locations

View can load from script tags or from files. To load from a script tag, create a script tag with your template and an id like:

<script
 type='text/ejs'

 id='recipes'

>

<% for
(var
 i=0
; i < recipes.length; i++){ %>
  <li><%=recipes[i].name %></li>
<%} %>

</script
>

Render with this template like:

$("#foo
").html
('recipes',recipeData)

Notice we passed the id of the element we want to render.

Packaging Templates

If you're making heavy use of templates, you want to organize them in files so they can be reused between pages and applications.

But, this organization would come at a high price if the browser has to retrieve each template individually. The additional HTTP requests would slow down your app.

Fortunately, StealJS can build templates into your production files. You just have to point to the view file like:

steal.views('path/to/the/view.ejs');


This will pre-process the view and insert it into a compressed single file with your other JS code.

Note: Steal 1.1 will even let you not load the view engine in production if all your templates are packaged.

Asynchronous

By default, retrieving requests is done synchronously. This is fine because StealJS packages view templates with your JS download.

However, some people might not be using StealJS or want to delay loading templates until necessary. If you have the need, you can provide a callback paramter like:

$("#foo"
).html('recipes'
,recipeData, function
(result)
{

   this
.fadeIn()
});

The callback function will be called with the result of the rendered template and 'this' will be set to the original jQuery object.

Just Render Templates

Sometimes, you just want to get the result of a rendered template without inserting it, you can do this with $.View:

var
 out = $.View('path/to/template.jaml'
,{});

Preloading Templates

You can preload templates asynchronously like:

$.View('path/to/template.jaml'
,{}, function
()
{
});

When it comes time to use them in your app, they will be ready for the user.

Supported Templates

JavaScriptMVC comes with the following templates:

  • EmbeddedJS

    <h2
    >
    <%= message %>
    </h2
    >
    
    
  • JAML

    h2(data.message);
    
    
  • Micro

    <h2
    >
    {%= message %}</h2
    >
    
    
  • jQuery.Tmpl

    <h2
    >
    ${message}</h2
    >
    
    

Mustache is supported in a 2nd party plugin.

Using Other Templates:

Integrating into $.View (and StealJS's build process) is easy, you just have to register your script like:

$.View.register({
    suffix : "tmpl"
,
    renderer: function
( id, text )
 {

        return
 function
(data)
{

            return
 jQuery.render( text, data );
        }
    },
    script: function
( id, text )
 {

        var
 tmpl = $.tmpl(text).toString();
        return
 "function(data){return ("
+
            tmpl+
            ").call(jQuery, jQuery, data); }"
;
    }
})

Here's what each property does:

  • suffix - files that use this suffix will be processed by this template engine
  • renderer - returns a function that will render the template provided by text
  • script - returns a string form of the processed template function.

Conclusion

Templates are great, but there's a lot of extra work that goes into making a template engine useful. But, almost all of that extra work can be abstracted and reused.

This is exactly what jQuery.View is! It's a tool so future template engines don't have to worry about loading, caching, and bundling templates.

Even better, as it is a uniform template API, it enables plugin authors to write widgets that accept arbitrary template types.

I personally feel like this would be a good canidate for jQuery an official jQuery plugin of its own. Imagine customizing the layout of a widget by passing it a template:

$("#upcoming
").srchr_search_result
({
    modelType : Srchr.Models.Upcoming,
    resultView : "//srchr/views/upcoming.ejs"


}

);

P.S. This is actual code from our JavaScriptMVC version of Srchr . Read about it here . We customize search results panels with a Model used to retrieve searches and a view to output the results.

 

原文:http://jupiterjs.com/news/organizing-a-jquery-application#news/jquery-view-client-side-templates-for-jquery

分享到:
评论

相关推荐

    Addison.Wesley.C++.Templates-The.Complete.Guide.chm

    Addison.Wesley.C++.Templates-The.Complete.Guide.chm 值得看看。

    Addison.Wesley.C++.Templates-The.Complete.Guide.rar

    《Addison.Wesley.C++.Templates-The.Complete.Guide》是一本深入探讨C++模板技术的专业书籍,由David Vandevoorde和Nicolai M. Josuttis撰写,旨在为程序员提供全面、详尽的C++模板知识。这本书是C++程序员理解和...

    PyPI 官网下载 | acid.senza.templates-1.6-py3-none-any.whl

    《PyPI官网下载:acid.senza.templates-1.6-py3-none-any.whl》 在Python的世界里,PyPI(Python Package Index)是官方的软件仓库,它为开发者提供了无数的第三方库,使得开发工作更加高效便捷。本文将详细探讨...

    Python库 | janis-pipelines.templates-0.9.4.tar.gz

    资源分类:Python库 所属语言:Python 资源全名:janis-pipelines.templates-0.9.4.tar.gz 资源来源:官方 安装方法:https://lanzao.blog.csdn.net/article/details/101784059

    C...Templates.-.Theplete.Guide

    C...Templates.-.Theplete.GuideC...Templates.-.Theplete.Guide

    Node.js-email-templates用于在Node.js中创建预览和发送自定义电子邮件模板

    **Node.js电子邮件模板库——email-templates** 在Node.js环境中,`email-templates`是一个强大的工具,它使得创建、预览以及发送自定义的电子邮件模板变得简单易行。这个库的目的是提供一种灵活且高效的方式来处理...

    PyPI 官网下载 | acid.senza.templates-1.92-py3-none-any.whl

    标题中的"PyPI 官网下载 | acid.senza.templates-1.92-py3-none-any.whl"指的是一个在Python Package Index (PyPI) 官网上发布的软件包。PyPI是Python社区用来分发开源软件的主要平台。在这个特定的例子中,我们关注...

    PyPI 官网下载 | acid.senza.templates-1.1.tar.gz

    标题中的"PyPI 官网下载 | acid.senza.templates-1.1.tar.gz"表明这是一个在Python Package Index(PyPI)官方源上发布的软件包,名为`acid.senza.templates`,版本为1.1,其打包格式是tar.gz。PyPI是Python开发者...

    jquery-1.10.2.js

    jquery-1.10.2.js

    [计算机科学经典著作].C...Templates.-.Theplete.Guide

    [计算机科学经典著作].C...Templates.-.Theplete.Guide c++模版有关的 以前无意从电驴上下载的计算机名著系列,现在0积分提供给大家。内容涉及很多方面,c++尤其多。大部分为英文 ,极少数为中文,若该书内容介绍错...

    els-cas-templates.zip

    【标题】"els-cas-templates.zip"是一个包含爱思唯尔(Elsevier)出版物的LaTeX模板的压缩文件。这些模板旨在帮助作者按照"your paper your way"的理念,以标准化格式准备科研论文。 【描述】中的"单栏、双栏模板"指...

    transport.js

    冲突的原因是jquery给一个object增加了很多元素,那么在Object.prototype.toJSONString = function () 这个函数中 for (k in this) 语句中进行了无数次的循环,导致网页很卡,并且在IE中会报错。 解决方案: ...

    percona-zabbix-templates-1.1.6-11.noarch.rpm

    标题中的"percona-zabbix-templates-1.1.6-11.noarch.rpm"是这套模板的特定版本,其中"1.1.6"代表版本号,"11"可能表示修订或更新次数,".noarch.rpm"则表明这是一个跨平台的RPM(Red Hat Package Manager)软件包,...

    Laravel开发-client-templates

    "Laravel开发-client-templates"意味着我们要探讨如何在Laravel项目中管理和使用客户端模板来创建高效且用户体验良好的Web应用。 首先,Laravel的MVC(Model-View-Controller)架构中,视图(View)部分就是用于...

    前端项目-jquery.loadtemplate.zip

    - 数据驱动视图:在MVVM(Model-View-ViewModel)架构中,模板引擎常用于数据绑定。 总的来说,`jquery.loadtemplate` 插件是前端开发中的一个实用工具,它简化了模板管理和数据渲染的过程,提高了开发效率。虽然...

    Python库 | pyats.templates-19.0-py3-none-any.whl

    python库。 资源全名:pyats.templates-19.0-py3-none-any.whl

    mysql-cacti-templates-1.1.3.tar.gz

    MySQL-Cacti-Templates-1.1.3是一款专为Cacti监控系统设计的数据库模板,用于更有效地监控MySQL服务器的性能。Cacti是一款开源的网络监控和图形生成工具,广泛应用于网络管理员和系统管理员,以追踪网络设备、服务器...

Global site tag (gtag.js) - Google Analytics