存档

文章标签 ‘jst’

javascript template (4) 标准修改器

2008年3月6日 没有评论

1.  语法
竖线一定要和modifier紧邻。

${whatever_expression|modifier}   //OK${whatever_expression |modifier}  //OK${whatever_expresion | modifier} //BROKEN${whatever_expresion| modifier}  //BROKEN 2.标准modifier 

(1)capitalize

  • 将字符串变大写

(2)default:valueWhenNull

  • This modifier tests the expression for null. If null, the default modifier returns the valueWhenNull argument.
  • Note, if your expression is a top level variable, JavaScript makes\r\na distinction between null and undefined values. If your expression is\r\na top level variable reference and is undefined (instead of null),\r\nyou’ll get an exception, even if you try to protect the reference by\r\nusing the ”’default”’ modifier.
    • For example if\r\nsystemAdminMessage is null, the following will work fine. But, if\r\nsystemAdminMessage is undefined, the following will throw an exception.\r\n
      • <div class=”importantMessage”> ${systemAdminMessage|default:”"} </div>
    • To prevent the error, you can use the defined(str) helper function, in a protective if statement. For example…
      • {if defined(‘systemAdminMessage’)} <div class=”importantMessage”> ${systemAdminMessage|default:”"} </div> {/if}

(3)eat

  • 返回空字符串
  • 在想调用js函数,但不想输出东西时有用

(4)escape

  • Converts the characters of & to &amp;, < to &lt;, and > to &gt;.
  • useful to prevent Cross-Site Scripting attacks, preventing evildoers from injecting their own HTML or JavaScript into your pages.

(5) h

  • 同escape

3. 扩展自己的modifiers
        参考这里

分类: 开发 标签:

javascript template (3) 语法

2008年3月6日 没有评论
  1. expressions and expressions modifiers 表达式和表达式修改器
  ${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}
  • expr是合法的javascript表达式,’}'除外
  • modifier的格式    modifierName[:argExpr1[,argExpr2[,argExprN]]]
  • argExpr是一个expr

示例:

  ${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}

如果expression里含有'{','}'字符,不能再使用${expression}了,可以使用${%expression%}


2. control flow 控制流

  {if testExpr}
    {elseif testExpr}
    {else}
  {/if}
  • testExpr是合法的js表达式,’}'除外
  • testExpr不需要括号括起来

示例:

  {if customer != null && customer.balance > 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>

3. Loops 循环

  {for varName in listExpr}
  {/for}

  {for varName in listExpr}
    ...main body of the loop...
  {forelse}
    ...body when listExpr is null or listExpr.length is 0...
  {/for}
  • varName是合法的js变量名
  • listExpr必须是js的数组或Object或null,The listExpr is evaluated only once.
  • 在循环体内可以使用varName_index来索引

示例:

  {for x in customer.getRecentOrders()}
    ${x_index} : ${x.orderNumber} <br/>
  {forelse}
    You have no recent orders.
  {/for}

4. variable declarations 变量声明

  {var varName}
  {var varName = varInitExpr}
  • varName是合法的js变量名
  • varInitExpr不能含有’}'字符

示例:

  {var temp = crypto.generateRandomPrime(4096)}
  Your prime is ${temp}.  

5. macro declarations 宏定义

  {macro macroName(arg1, arg2, ...argN)}
    ...body of the macro...
  {/macro}
  • 宏相当于js的函数,不同的是宏的体内是符合jst语法的语句和表达式,而不是js语句
  • macroName是任何合法的js变量名
  • 返回值类型是string
  • 通过${macroName()}这种方式调用

示例:

  {macro htmlList(list, optionalListType)}
    {var listType = optionalListType != null ? optionalListType : "ul"}
    <${listType}>
      {for item in list}    
        <li>${item}</li>
      {/for}
    </${listType}>
  {/macro}

  Using the macro...
  ${htmlList([ 1, 2, 3])}
  ${htmlList([ "Purple State", "Blue State", "Red State" ], "ol")}
  {var saved = htmlList([ 100, 200, 300 ])}
  ${saved} and ${saved}
关于宏的作用域:
Regarding macro scope: by default, macros are defined private to each template. If you want to
export a macro so that it can be reused in other templates (such as building up a helper
library of macros), one approach is to save a reference to your macro into your
''contextObject''. For example, in the ''contextObject'' that's the argument to
''template.process(contextObject)'', you can set ''contextObject['exported'] = {};''
before you call process(). Then, here's how you can capture a macro into
''contextObject['exported']''...
  {macro userName(user)}
    {if user.aliasName != null && user.aliasName.length > 0}
      ${user.aliasName}
    {else}
      ${user.login}
    {/if}
  {/macro}
  ${exported.userName = userName |eat}
Cleverly, you might also set ''contextObject['exported'] = contextObject;''  It's circular,
but it works.

6. CDATA text section

  {cdata}
    ...text emitted without JST processing...
  {/cdata}

  {cdata EOF}
    ...text emitted without JST processing...
  EOF
被包含的text不会被jst处理,This can be useful if you're using a JavaScript Template to
generate a JavaScript Template.
  • EOF可以是任意的标识符,当然不能包含’}',用来标识text的结尾
  • ‘…’可以包含任何东西,如果有换行,jst将原封不动的返回一个换行

示例:

Hello, ${user.firstName}.
An example of expression markup in JST looks like
{cdata END_OF_THE_CDATA_SECTION}
${customer.firstName} ${customer.lastName}
END_OF_THE_CDATA_SECTION
which shows a customer‘s name.

Let me repeat that…
{cdata}
${customer.firstName} ${customer.lastName}
{/cdata}
…will show a customer’s name.


输出结果是:
Hello, Steve.
An example of expression markup in JST looks like

${customer.firstName} ${customer.lastName}

which shows a customer‘s name.

Let me repeat that…

${customer.firstName} ${customer.lastName}

…will show a customer’s name.


7 in-line javascript 内嵌js
(1) eval block

  {eval}
    ...javascript evaluated during JST processing...
  {/eval

  {eval EOF}
    ...javascript evaluated during JST processing...
  EOF
  • EOF的要求同上
  • The {eval} markup block can be useful to define multi-line JavaScript event handler functions near where they are used.

示例:

  <select onchange="sel_onchange()"></select>
  {eval}
    sel_onchange = function() {
     ...Do some complicated javascript...;
     ...more js code here...;
    }
  {/eval}
请注意,这里没有在sel_onchange上使用'var'关键词,主要是确保sel_onchange处于全局域,hence
usable as an event handler function.event handler function 一定要全局域吗?待考。
(2)minify block
{minify}
multi-line text which will be stripped of line-breaks during JST processing
{/minify

{minify EOF}
…multi-line text which will be stripped of line-breaks during JST processing…
EOF

  • EOF要求同上
  • A {minify} block allows you to inline long JavaScript or CSS code into your HTML attributes. For JavaScript, this is especially useful for event handlers like onchange, onmousedown, onfocus, onblur, etc. Without {minify}, handling linebreaks or newlines in long JavaScript code is possible but unwieldy.

示例:

<select onchange="{minify}
     ...Do some complicated multi-line javascript...;
     ...more js code here...;
     this.enabled = false;
  {/minify}">

  <select onchange="{minify END_OF_JS}
     ...Do some complicated multi-line javascript...;
     ...more js code here...;
     this.enabled = false;
  END_OF_JS">

The {minify} block is also useful to make long inline CSS <style> attributes readable and maintainable, which can sometimes be useful in Internet Explorer which does not seem to support dynamically generated <style> tags.

<div id=“commentPanel”
style={minify}
display:none;
margin: 1em;
border: 1px solid #333;
background: #eee;
padding: 1em;
{/minify}
>

</div>


辅助函数:defined(str)

  • 判断str是否有定义

示例:

  {if defined('adminMessage')}
    System Administrator Important NOTICE: ${adminMessage}
  {/if}
分类: 开发 标签:

javascript templates (2) 示例

2008年2月29日 没有评论

从上一篇的JST API介绍可以得出两种使用JST的方法。

一、隐藏的textarea

<!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”>
<head>
<title>test</title>
<script type=“text/javascript” src=“trimpath.js”></script>
<script language=“javascript” type=“text/javascript”>
function showContent(){
var tplOb = TrimPath.parseDOMTemplate(“tpl_jst”);
var data = {
name : “robert”,
sayHello : function(name){
return “hello, ” + name;
}
};

document.getElementById(“show”).innerHTML = tplOb.process(data);
}
</script>
</head>

<body>
<div id=“show” style=“width:200px;height:50px;border:1px solid #ccc;margin-bottom:20px;text-align:center;”>
click the button
</div>
<input type=button value=“click me” onclick=“showContent();” />
<textarea id=“tpl_jst” style=“display:none;”>
${sayHello(name)}
</textarea>
</body>
</html>

二、符合JST语法的字符串

<!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”>
<head>
<title>test</title>
<script type=“text/javascript” src=“trimpath.js”></script>
<script language=“javascript” type=“text/javascript”>
function showContent(){
var tplOb = TrimPath.parseTemplate(“
${sayHello(name)}“);
var data = {
name : “robert”
};

document.getElementById(“show”).innerHTML = tplOb.process(data);
}

function sayHello(name){
return “hello, ” + name;
}
</script>
</head>

<body>
<div id=“show” style=“width:200px;height:50px;border:1px solid #ccc;margin-bottom:20px;text-align:center;”>
click the button
</div>

<input type=button value=“click me” onclick=“showContent();” />
</body>
</html>

从上面的两个例子可以看出,对于在jst中使用函数的情况,函数可以定义在contextObject中,也可以是全局的函数,只要能找到就ok,上篇文章中说访问的是contextObject.func,造成一定的困惑,其实对于函数两种方式都可以。

分类: 开发 标签:

javascript templates (1) 介绍

2008年2月29日 没有评论

一、简介

For web application developers, the ”’JavaScript Templates”’ engine from TrimPath is a lightweight APL / GPL open-source component that lets you have template-based programming (like PHP/ASP/JSP) while running in a web browser.

  • The ”’JST”’ engine is written entirely in standard JavaScript.
  • It supports a productive template markup syntax very much like FreeMarker, Velocity, Smarty.
  • JST is a readable alternative to manually coded massive String concatenations and major DOM/DHTML manipulations.

二、API
包含了jst的js文件后,就拥有了一个全局对象:TrimPath
1. TrimPath有以下辅助函数
函数1      TrimPath.parseTemplate(templateContentStr, optionalTemplateName)
参数说明:
templateContentStr
符合JST语法的字符串,例如: “Hello ${firstName} ${lastName}”
optionalTemplateName
一个可选的字符串用来指定模板名称,辅助查错
返回值:
解析templateContentStr模板,返回templateObject,若出错抛异常

函数2    TrimPath.parseDomTemplate(elementId, optionalDocument)
参数说明:
elementId
此DOM元素的innerHTML作为模板
optionalDocument
可选参数,在使用iframe,frameset或者多文档时会有用,默认为document
返回值:
templateObject,是一个中间变量,表示一个成功解析的模板。
若出错抛异常
说明:
DOM元素一般使用隐藏的textarea,如
<textarea id=”elementId” style=”display:none;”> template body </textarea>
此函数等价于 :

var templateStr = document.getElementById(“elementId”).innerHTML;

return TrimPath.parseTemplate(templateStr);
函数3      TrimPath.processDomTemplate(elementId, contextObject, optionFlags, optionalDocument)
等价于:

var templateObject = TrimPath.parseDomTemplate(elementId, optionalDocument);

return templateObject.process(contextObject, optionFlags);
参数含义分别见TrimPath.parseDomTemplate和templateObject.process

2. 中间变量templateObject,一个核心方法
函数         templateObject.process(contextObject, optionFlags)
参数说明:
contextObject
1. 必须是Object,在模板里的${a}就是访问contextObject.a,${a.b.c}就是访问
contextObject.a.b.c。
2. contextObject可以包含任意的JS对象,如字符串、数字、日期、对象和函数,
${groupCalender(new Date())} 将调用 contextObject.groupCalender(new Date()).
当然,在上下文环境中提供groupCalender()函数,返回值是string。
optionFlags
可以为null,也可以是
a、throwExceptions
默认是false,当true的时候,process() 方法将重新抛出异常,当false的时候,任何异常将                                      停止解析模板,并在方法返回值包含一个出错信息
b、keepWhitespace
默认false。
When true, all whitespace characters are emitted during template processing.
When false, various whitespace characters (newline, space, tab) that                               surround  statement tags (such as {if}, {else}, {for}) are stripped out to make any output look “cleaner and prettier”.
返回值:
将contextObject的参数注入到模板后生成的string
说明:
此函数可以多次调用,没有解析模板的性能开销,因此缓存和重复使用templateObject有助于提高性                    能。

参考:
· 主页
· 中文翻译

分类: 开发 标签: