Skip to content

Instantly share code, notes, and snippets.

@ritalin
Created December 26, 2012 10:00
Show Gist options
  • Save ritalin/4379305 to your computer and use it in GitHub Desktop.
Save ritalin/4379305 to your computer and use it in GitHub Desktop.
PHPTALの不可解な挙動
<ul tal:repeat="item items">
  <li tal:content="item" />
</ul>

というテンプレートに対して、

$tal->items => [1, 2, 3,...]

という値を渡すと、

<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  ...
</ul>

となってくれるのに、

<ul tal:repeat="item parent/items">
  <li tal:content="item" />
</ul>

というテンプレートに対して、

$tal->parent = [
    'items' => [1, 2, 3,...]
];

という値を渡すと、

<ul><li>1</li></ul>
<ul><li>2</li></ul>
<ul><li>3</li></ul>
...

ってなる。

<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  ...
</ul>

となってほしいのに...

諸元 PHPTAL-1.2.2

@tanakahisateru
Copy link

これは:

<?php
$template = new PHPTAL;
$template->setSource(
'<ul tal:repeat="item items">
  <li tal:content="item" />
</ul>');
$template->items = [1, 2, 3];
echo $template->execute() . "\n";

こうなりました:

<ul>
  <li>1</li>
</ul><ul>
  <li>2</li>
</ul><ul>
  <li>3</li>
</ul>

これも:

$template = new PHPTAL;
$template->setSource(
'<ul tal:repeat="item parent/items">
  <li tal:content="item" />
</ul>');
$template->parent = [
    'items' => [1, 2, 3],
];
echo $template->execute() . "\n";

こう:

<ul>
  <li>1</li>
</ul><ul>
  <li>2</li>
</ul><ul>
  <li>3</li>
</ul>

コンテキスト変数の構造は関係ないっぽいです。

TALで繰り返しを正しくやる方法は:

<?php
$template = new PHPTAL;
$template->setSource(
'<ul>
  <li tal:repeat="item items" tal:content="item" />
</ul>');
$template->items = [1, 2, 3];
echo $template->execute() . "\n";

で、なんでこういうふうに、外枠ではなく要素に repeat が付くのかというと、

$template->data = ['ほげ', 'ふが', 'にょろ'];

のとき、

<h1>我らほげ軍団</h1>
<p>ほげ</p>
<p>ふが</p>
<p>にょろ</p>

というHTMLを出力したい時にどう書くかを考えると、 repeat を入れ物ではなく「繰り返す要素」にしないといけない仕様の意図を理解できます。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment