将MySQL行分配给Smarty

时间:2011-03-06 21:03:52

标签: php smarty

我在一个项目上使用Smarty,我发现自己在Smarty模板中的字符串格式化方面做得太多,从而挫败了使用Smarty的目的。对于来自MySQL的数据尤其如此,通常需要格式化stripslashesreplace

我想在PHP端而不是在模板中进行这种类型的格式化,但我不确定如何将数据从MySQL分配给Smarty,然后对它进行itierate。这是我用来将MySQL中的行分配给Smarty的PHP:

while ($entry = $getBlogEntries->fetch()) {
    $entries[] = $entry;
}

一个简单的数组,每行都被提取,没有格式化。然后分配:

$smarty->assign('blogEntries', $entries);

最后迭代过来:

{section name=entries loop=$blogEntries}<div class="blogEntry-middle-index">
                    <a class="postTitle" href="/blog/entry/{$blogEntries[entries].id}">{$blogEntries[entries].blogTitle|stripslashes}</a>
                    {$blogEntries[entries].blogBody|stripslashes}
                </div>{/section}

我想要完成的是能够在将PHP数据分配给Smarty之前格式化PHP中的行数据,然后在我的Smarty模板中进行迭代。

非常感谢任何帮助。谢谢!

2 个答案:

答案 0 :(得分:1)

遍历条目数组并在计划传递给Smarty的元素上调用htmlentites()。将它们存储到Smarty将接收的新阵列中。

// Get all the entires on an array like you have done
while ($entry = $getBlogEntries->fetch()) {
  $entries[] = $entry;
}

// New array for Smarty
$smarty_entries = array();

foreach ($entries as $entry)
{
  // Add each element from $entries onto the array for Smarty
  // Calling stripslashes and htmlentites on the fields Smarty will use
  $smarty_entires[] = array(
     "id" => htmlentities(stripslashes($entry['id']),ENT_QUOTES),
     "blogBody" => htmlentities(stripslashes($entry['blogBody']),ENT_QUOTES),
     // Other parts of the entry
  );
}
$smarty->assign('blogEntries', $smarty_entries);

// Now in your smarty template you don't need the stripslashes or escape modifiers

答案 1 :(得分:0)

使用Smarty 3,您还可以创建一个变量过滤器来自动处理Smarty变量的擒纵机构。看这篇文章:

http://www.smarty.net/forums/viewtopic.php?t=18926