Http://trimpath.com/project/wiki/JavaScriptTemplates
Trimpath JavaScript is a lightweight, JavaScript-based, cross-browser, open source code protocol using APL/GPL, allowing you to easily implement a pure JS Engine Based on Template programming.
Reference content 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.
Website address:
Http://trimpath.com/project/wiki/JavaScriptTemplates
If you cannot wait to see my translation or are not satisfied with the translation quality, please refer to the original English version of the website above.
Quick Demonstration:
Reference content <Head>
<Script language = "javascript" src = "trimpath/template. js"> </script>
</Head>
<Body>
<Div id = "outputDiv">
</Div>
<Script language = "javascript">
Var data = {
Products: [{name: "mac", desc: "computer ",
Price: 1000, quantity: 100, alert: null },
{Name: "ipod", desc: "music player ",
Price: 200, quantity: 200, alert: "on sale now! "},
{Name: "cinema display", desc: "screen ",
Price: 800, quantity: 300, alert: "best deal! "}],
Customer: {First: "John", last: "public", level: "gold "}
};
</SCRIPT>
<Textarea id = "cart_jst" style = "display: none;">
Hello $ {customer. First }$ {customer. Last}. <br/>
Your shopping cart has $ {products. Length} item (s ):
<Table>
<Tr> <TD> name </TD> <TD> description </TD>
<TD> price </TD> <TD> quantity & alert </TD> </tr>
{For P in products}
<Tr> <TD >$ {P. Name | capitalize} </TD> <TD >$ {P. DESC} </TD>
<TD> $ {P. price} </TD> <TD >$ {P. quantity }:$ {P. alert | default: "" | capitalize} </TD>
</Tr>
{Forelse}
<Tr> <TD colspan = "4"> no products in your cart. </tr>
{/}
</Table>
{If customer. Level = "gold "}
We love you! Please check out our gold customer specials!
{Else}
Become a gold customer by buying more stuff here.
{/If}
</Textarea>
<Script language = "javascript">
// The one line processing call...
Var result = TrimPath. processDOMTemplate ("cart_jst", data );
// Voila! That's it -- the result variable now holds
// The output of our first rendered JST.
// Alternatively, you may also explicitly parse the template...
Var myTemplateObj = TrimPath. parseDOMTemplate ("cart_jst ");
// Now, callto myTemplateObj. process () won't have parsing costs...
Var result = myTemplateObj. process (data );
// Setting an innerHTML with the result is a common last step...
Document. getElementById ("outputDiv"). innerHTML = result;
// You might also do a document. write () or something similar...
</Script>
</Body>
</Html>
Actual results:
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.
Reference content <script language = "javascript" src = "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:
Reference content <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.
The reference content is as follows:
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:
REFERENCE The templateContentStr 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 referenced content parameter contextObject 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 reference content parameter optionalFlags 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.
Reference content 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:
Reference content 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
Reference content $ {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
Reference content $ {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:
Reference content 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
Reference content {if testExpr}
{Elseif testExpr}
{Else}
{/If}
The above testexpr is a legal JavaScript Criterion
Example
Reference content {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 = "/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.
Reference content {if defined ('adminmessage ')}
System Administrator Important NOTICE :$ {adminMessage}
{/If}
Loop statement
Reference content {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
Reference content 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
Reference content {var varName}
{Var varName = varInitExpr}
* VarName must be a valid javascript variable name.
* VarInitExpr must be a string that does not contain "}"
Example:
Reference content {var temp = crypto. generateRandomPrime (4096 )}
Your prime is $ {temp }.
Macro definition
Reference content {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
Reference content {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.
Reference content * 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, but if you want to define
For a macro library, you may need to define the macro to be exported before process (): contextobject ['exported'] = {};
The following is an example:
Reference content {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
[Code]
{CDATA}
... Text emitted without JST processing...
{/CDATA}
{Cdata eof}
... Text emitted without JST processing...
EOF
Not yet resumed. Please view the original English content...
========================================================== ======================
The following code is displayed in the code of viewing the 163 blog, which helps to use Trimpath -- template
Reference Content function createJST (jstId, jstContent) {var textarea = document. createElement ('textarea '); textarea. value = jstContent; textarea. id = jstId; textarea. style. display = 'none'; document. body. appendChild (textarea );}
Function createJSTAndParse (jstId, jstContent) {createJST (jstId, jstContent); return TrimPath. parseDOMTemplate (jstId );}
The usage is as follows:
Reference content var content = createJSTAndParse ("HTML TemplateID", "HTML TemplateContent"). process ({});