Get Smarty

Donate

Paypal

Smarty Icon

You may use the Smarty logo according to the trademark notice.

Smarty Template Engine Smarty Template Engine

For sponsorship, advertising, news or other inquiries, contact us at:

Sites Using Smarty

Advertisement

{assign}

{assign} は、テンプレート変数を テンプレートの実行時に 代入します。

Note

テンプレート内で変数に代入するというのは、 本質的にはアプリケーションのロジックをプレゼンテーションに持ち込んでいることになります。 これは本来 PHP 側でやったほうがうまく処理できることでしょう。 自己責任のもとで使いましょう。

Note

テンプレート変数を代入するときの 短縮形 も参照ください。

属性

属性名 必須 デフォルト 概要
var string Yes n/a 代入される変数の名前
value string Yes n/a 代入される値
scope string No n/a 代入する変数のスコープ。'parent'、'root' あるいは 'global'

オプションのフラグ

名前 概要
nocache 変数を 'nocache' 属性つきで代入する

Example 7.8. {assign}


{assign var="name" value="Bob"}
{assign "name" "Bob"} {* 短縮形 *}

The value of $name is {$name}.

  

上の例の出力は次のようになります。


The value of $name is Bob.

  

Example 7.9. nocache を指定した変数による {assign}


{assign var="name" value="Bob" nocache}
{assign "name" "Bob" nocache} {* 短縮形 *}

The value of $name is {$name}.

  

上の例の出力は次のようになります。


The value of $name is Bob.

  

Example 7.10. 計算結果の {assign}


{assign var=running_total value=$running_total+$some_array[$row].some_value}

  

Example 7.11. 呼び出し元テンプレートのスコープでの {assign}

インクルードされたテンプレート内で代入した変数は、インクルードした側のテンプレートからも見えます。


{include file="sub_template.tpl"}
...
{* サブテンプレートで代入した変数を表示します *}
{$foo}<br>
...

  

上のテンプレートでインクルードしている sub_template.tpl の例を次に示します。


...
{* foo はインクルード元のテンプレートからも見えます *}
{assign var="foo" value="something" scope=parent}
{* bar はこのテンプレート内でしか見えません *}
{assign var="bar" value="value"}
...


Example 7.12. 現在のスコープツリーへの変数の {assign}

現在のツリーのルートに変数を代入することができます。この変数は、同じツリーを使うすべてのテンプレートから見えるようになります。


{assign var=foo value="bar" scope="root"}

  

Example 7.13. グローバル変数の {assign}

グローバル変数は、すべてのテンプレートから見えます。


{assign var=foo value="bar" scope="global"}
{assign "foo" "bar" scope="global"} {* 短縮形 *}

  

Example 7.14. {assign} された変数への PHP スクリプトからのアクセス

{assign} した変数に PHP スクリプトからアクセスするには getTemplateVars() を使います。 このテンプレートでは、変数 $foo を作ります。


{assign var="foo" value="Smarty"}

テンプレート変数にアクセスできるのは、テンプレートの実行中か実行後のみです。 次のスクリプトのようになります。


<?php

// まだテンプレートを実行していないので、これは何も出力しません
echo $smarty->getTemplateVars('foo');

// テンプレートを変数に取り込みます
$whole_page = $smarty->fetch('index.tpl');

// テンプレートを実行した後なので、これは 'smarty' を出力します
echo $smarty->getTemplateVars('foo');

$smarty->assign('foo','Even smarter');

// これは 'Even smarter' を出力します
echo $smarty->getTemplateVars('foo');

?>


次にあげる関数にも、オプションで テンプレート変数を代入することができます。

{capture}, {include}, {include_php}, {insert}, {counter}, {cycle}, {eval}, {fetch}, {math}, {textformat}

{$var=...}assign() および getTemplateVars() も参照ください。

Comments
No comments for this page.

Advertisement

Sponsors [info]

Sponsors