2011-03-06 81 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