Javascript template JST template engine-trimpath)

Source: Internet
Author: User

[Template reprint] JavaScript template JST template engine ---- trimpath

Reprint Web site: http://bbs.javascript.com.cn/simple/index.php? T1022.html

Http://trimpath.com/project/wiki/JavaScriptTemplates

Trimpath Javascript is not lightweight, JavaScript-based, cross-browser, using the APL/GPL open source code protocol, you can easily implement a pure JS Engine Based on Template programming.

It has the following features:
1. It is written in standard JavaScript and supports cross-browser
2. The template syntax is similar to freemarker, velocity, and smarty.
3. Use a simple language to describe large-segment strings and DOM/DHTML operations
4. You can easily parse the data in the XML file format to the specified template.

This engine can be used to completely handle view tasks. The server module can directly output data. Making your MVC model integrated, and because the view is handled by the browser, greatly reducing the burden on the server, it is a good choice to build the Network Information System Application of Ajax technology. Next we will introduce the use of this JST engine by translating the site's articles.

Hred
About JST in 10 minutes

JST API
JST markup syntax
JST standard Modifiers
JST downloads
JST community Wiki
JST browser compatibility
JST Online Demo

1. API
First download template. js from the download page
And then reference it in your JSP/asp/PHP files.

<Script language = "JavaScript" src = http://bbs.chinaunix.net/"trimpath/template. js"> </SCRIPT>

After you reference the template. js file, the script will create an object named "trimpath" for you to use.

Trimpath object

This object is a global single variable and an access portal for all trimpath components. Apart from its own, we try to create a clear namespace for you to use.

The method defined by trimpath is as follows:

Trimpath. parsedomtemplate (elementid, optionaldocument)

Obtain the innerhtml of the DOM component whose ID is elementid on the page and parse it into a template. This method returns a templateobject (which will be described in detail below ), an exception is thrown when an parsing error occurs. The following is the parameter of this method:
Elementid Dom component, whose innerhtml will be used as a template
Optionaldocument is an optional parameter. It is useful when IFRAME, frameset, or multi-document by default.
The Dom Element Used for template creation is a hidden <textarea>, as shown in the following example:

<Textarea id = "elementid" style = "display: none;"> template body </textarea>

 

Trimpath. processdomtemplate (elementid, contextobject, optionalflags, optionaldocument)
An auxiliary function that calls the trimpath. parsedomtemplate () and then the process () methods to obtain the templateobject. The output is the object returned in templateobject. Process. An error will be thrown when parsing errors. Below are the parameters for this method:

Elementid contains the DOM element ID of the template content
Contextobject refer to templateobject. Process ()
For more information about optionalflags, see templateobject. Process ()
For optionaldocument, see trimpath. parsedomtemplate.

Trimpath. parsetemplate (templatecontentstr, optionaltemplatename)
Parse the template method. parse a string as a template and return a templateobject.
Parameter table:

Templatecontentstr: a string that conforms to the JST syntax, for example, "Hello $ {firstname }$ {lastname }"
An optional string of optionaltemplatename is used to specify the Template Name.

The templateobject
Trimpath. parsetemplate () and trimpath. parsedomtemplate () run successfully to generate a templateobject with only one primary method.

Templateobject. Process (contextobject, optionalflags)

This method combines the template and data and can be called repeatedly. If no re-resolution is performed, the caching and reuse of templateobjects will achieve the best system performance. The return value of this function is a string of a "rendered" template.

The contextobject parameter must be an object and will become an access domain of the template. For example, if a template is $ {A}, contextobject. A must be accessible. Similarly, $ {A. B. C}, contextobject. A. B. C can also be accessed.
Note: contextobject can be any object in Javascript, including strings, numbers, dates, objects, and functions. Therefore, $ {groupcalender (new date ()} Can call contextobject. groupcalender (new date () in this way ()). Of course, you must program the groupcalender () function by yourself.

The optionalflags parameter can be a null value or an object described in the following list:
The default value of throwexceptions is false. When the value is true, the process () method throws an exception again. When the value is false, the parsing template is stopped for any exception and the returned value contains an error message.
Keepwhitespace is falsel by default. When the value is true, the blank space of the template is retained. If it is set to false, white spaces (line breaks, spaces, and tabs) are truncated.

String. Prototype. Process () method

String. Prototype. Process (contextobject, optionalflags)
As a convenient way to add a process () method to the string object, let it execute the action of parsing the template. The parameter is the same as process.

VaR result = "Hello $ {firstname}". Process (data)
//... Is equivalent...
VaR result = trimpath. parsetemplate ("Hello $ {firstname}"). Process (data );

Add custom identifier

If you want to use custom identifiers, you must put them in the _ modifers object. These identifiers will be added to the contextobject object and finally passed to process () for parsing. Each custom identifier must be a function with at least one string parameter input and one string output.
Example:

[Copy to clipboard] [-]
Code:
VaR mymodifiers = {
Hello: function (STR, greeting ){
If (greeting = NULL)
Greeting = "hello ";
Return greeting + "," + STR;
},
Zerosuffix: function (STR, totallength ){
Return (STR + "000000000000000"). substring (0, totallength );
}
};
VaR mydata = {
Firstname: "John ",
Getcurrentpoints: function () {/* do something here... */return 12 ;}
}

Mydata. _ modifiers = mymodifiers;

"$ {Firstname}". Process (mydata) = "John"

"$ {Firstname | Hello}". Process (mydata) = "hello, John"
"$ {Firstname | Hello:" buanodias "}". Process (mydata) = "buanodias, John"
"$ {Firstname | Hello:" buanodias "| capitalize}". Process (mydata) = "buanodias, John"

"$ {Getcurrentpoints ()}". Process (mydata) = "12"
"$ {Getcurrentpoints () | zerosuffix: 4}". Process (mydata) = "1200"

JST syntax and statements

Syntax

$ {Expr}
$ {Expr | modifier}
$ {Expr | modifier1 | modifier2 |... | modifiern}
$ {Expr | modifier1: argexpr1_1}
$ {Expr | modifier1: argexpr1_1, argexpr1_2,..., argexpr1_n}
$ {Expr | modifier1: argexpr1_1, argexpr1_2 |... | modifiern: argexprn_1, argexprn_2,..., argexprn_m}

The expression can be any legal javascript string "}"
The identifier looks like this structure: modifiername [: argexpr1 [, argexpr2 [, argexprn]

Example of an expression with Parameters
$ {Customer. firstname}
$ {Customer. firstname | capitalize}
$ {Customer. firstname | default: "No Name" | capitalize}
$ {Article. getcreationdate () | default: new date () | tocalendercontrol: "YYYY. Mm. dd", true, "creation date "}
$ {(Lastquarter. calcrevenue ()-fixedcosts)/1000000}

An expression can also be identified by adding the "%" character like below, which can avoid errors in your expression when "}" occurs.

For example:
Visit our $ {% emitlink ('solutions and products ',
{Color: 'red', blink: false}) %} page.

The extra spaces are actually not necessary, like...
$ {% Customer. firstname %}
$ {% Customer. firstname | capitalize %}

Statement
The JST statement is like a javascript statement, and contains sentences such as if/else/For/function.

Branch control statement

{If testexpr}
{Elseif testexpr}
{Else}
{/If}

The above testexpr is a legal JavaScript Criterion

Example

{If customer! = NULL & amp; customer. Balance & gt; 1000}
We love you!
{/If}

{If user. Karma> 100}
Welcome to the black sun.
{Elseif user. ishero}
Sir, yes sir! Welcome!
{If user. lastname = "yen "}
Fancy some apple pie, sir?
{/If}
{/If}

<A href = http://bbs.chinaunix.net/"/login {If returnurl! = NULL & returnurl! = 'Main '}? Goto =$ {returnurl} {/if} "> login </a>

* The JST engine also contains a helper function defined (STR), which can be used to test whether a variable has been defined.

For example, this Code determines that the Administrator has sent a message to you.

{If defined ('adminmessage ')}
System Administrator Important Notice :$ {adminmessage}
{/If}

Loop statement

{For varname in listexpr}
{/}

{For varname in listexpr}
... Main Body of the loop...
{Forelse}
... Body when listexpr is null or listexpr. length is 0...
{/}

* Varname must be a valid JavaScript variable name.
* Listexpr can be an array, an object or an empty object, and can only be assigned once.
Example

Two variables are bound in the main body of the Loop:
_ LIST _ varname-holds the result of evaluating listexpr.
Varname_index-this is the key or counter used during iteration.

Examples:
{For X in customer. getrecentorders ()}
$ {X_index }:: {X. ordernumber} <br/>
{Forelse}
You have no recent orders.
{/}

Converted pseudo-code for the above...
VaR _ LIST _ x = Customer. getrecentorders ();
If (_ LIST _ x! = NULL & _ LIST _ x. length> 0 ){
For (VAR x_index in _ LIST _ x ){
VaR x = _ LIST _ x [x_index];
$ {X_index }:{$ X. ordernumber} <br/>
}
} Else {
You have no recent orders.
}

Define Variables

{Var varname}
{Var varname = varinitexpr}
* Varname must be a valid JavaScript variable name.
* Varinitexpr must be a string that does not contain "}"

Example:

{Var temp = crypto. generaterandomprime (4096 )}
Your Prime is $ {temp }.

Macro definition
{Macro macroname (arg1, arg2,... argn )}
... Body of the macro...
{/Macro}

* A macro is similar to a JavaScript function. The difference is that the main body of a macro is another JST template containing control statements and loop statements.

* The macro name must be a valid JavaScript variable name.
* The return value of a macro is a character
* Macro Syntax: $ {macroname ()}
An example of using macros

{Macro htmllist (list, optionallisttype )}
{Var listtype = optionallisttype! = NULL? Optionallisttype: "Ul "}
<$ {Listtype}>
{For item in list}
<Li >$ {item} </LI>
{/}
</$ {Listtype}>
{/Macro}

Using the macro...
$ {Htmllist ([1, 2, 3])}
$ {Htmllist (["Purple State", "Blue State", "red state"], "ol ")}
{Var saved = htmllist ([1, 100,200,300])}
$ {Saved} and $ {saved}

Run the preceding statement.
* 1
* 2
* 3
Such a list. You only need to assign the data list to the htmllist macro to list the data in the <li> mode, smart, you will soon change it to <option> <TD> and other applications.

Macro access domains are private to each template by default. However, if you want to define a macro library, you may need () previously, the macro that can be exported was defined as contextobject ['exported'] = {};
The following is an example:
{Macro username (User )}
{If user. aliasname! = NULL & User. aliasname. length> 0}
$ {User. aliasname}
{Else}
$ {User. login}
{/If}
{/Macro}
$ {Exported. Username = username | eat}
In addition, you can set contextobject ['exported'] = contextobject; it can also work normally.

CDATA Partition

{CDATA}
... Text emitted without JST processing...
{/CDATA}

{Cdata eof}
... Text emitted without JST processing...
EOF

This article from the csdn blog, reproduced please indicate the source: http://blog.csdn.net/zj1103/archive/2008/11/28/3400698.aspx

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.