Escaping Smarty Parsing

It is sometimes desirable or even necessary to have Smarty ignore sections it would otherwise parse. A classic example is embedding Javascript or CSS code in a template. The problem arises as those languages use the { and } characters which are also the default delimiters for Smarty.

在某些情況下我們希望 Smarty 能夠忽略樣版內的某些區塊,可是卻被編譯出來。典型 的例子是當我們在樣版內插入 Javascript 或 CSS 程式碼。會發生這些問題的原因在於這些語 言都是使用 { 與 } 字元,而剛好也是 Smarty 的預設阻斷符號。

The simplest thing is to avoid the situation altogether by separating your Javascript and CSS code into their own files and then using standard HTML methods to access them.

避免發生錯誤的最簡單方式是將 Javascript 與 CSS 檔放置在各自的檔案內,且使用 標準 HTML 語法取得這些檔案。

Including literal content is possible using {literal} .. {/literal} blocks. Similar to HTML entity usage, you can use {ldelim},{rdelim} or {$smarty.ldelim},{$smarty.rdelim} to display the current delimiters.

文字性的內容可以使用 {literal} .. {/literal} 區塊包入樣板中。 相同於 HTML 實體使用方式,你可以使用 {ldelim}{rdelim} 或是 {$smarty.ldelim}{$smarty.rdelim} 表示現在的阻斷符號。

It is often convenient to simply change Smarty's $left_delimiter and $right_delimiter.

通常而言要修改 Smarty $left_delimiter$right_delimiter 是很簡單的。

Example 3-7. 更改阻斷符號的範例

<?php

$smarty
= new Smarty;
$smarty->left_delimiter = '<!--{';
$smarty->right_delimiter = '}-->';
$smarty->assign('foo', 'bar');
$smarty->display('example.tpl');

?>

Where example.tpl is:

而 example.tpl 內容如後:

<script language="javascript">
var foo = <!--{$foo}-->;
function dosomething() {
    alert("foo is " + foo);
}
dosomething();
</script>