2011-03-06 84 views
1

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

我想在PHP端而不是在模板上进行这种格式化,但我不确定如何将数据从MySQL分配给Smarty,然后再通过它进行处理。这里是我一直在用的行分配从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之前然后在我的Smarty模板中迭代。

任何帮助将不胜感激。谢谢!

回答

1

循环遍历入口数组,并调用htmlentites()覆盖您计划传递给Smarty的元素。将它们存储到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 
+0

技术上讲,你并不需要首先创建'$ entries'阵列。你可以在'fetch()'循环中''smarty_entries'数组中创建'$ smarty_entries'数组来代替'$ entries',除非你需要在你的脚本中调用'fetch()'调用的未经过滤的原始输出。 – 2011-03-06 21:37:34

+0

这样做的窍门,谢谢!可以轻松地通过一个函数传递每个条目,以进一步完成它。我不打算多使用Smarty,但是当我这样做时,我想保持它的开发者所期望的那种。:) – NightMICU 2011-03-06 21:50:37

+0

我以前很少使用Smarty,但现在很依赖它。这是相当强大和精心设计的海事组织 – 2011-03-06 21:59:30