2016-12-13 4 views
4

저는 현명하지 못합니다. 나는 현명하게 PHP 함수를 사용하는 법을 알고 싶다. 일부 기능을 곧바로 사용할 수 있음을 이해합니다.Smarty에서 PHP 함수 세트를 사용하는 방법

예 : 내가 유식과 함께 PDO를 사용하고 {$my_string|strip_tags}

. 내 게시물을 얻을 코드를 아래에서 참조하십시오.

$stmnt = $conn->prepare("SELECT post_id, post_title FROM posts ORDER BY post_id DESC"); 
$stmnt ->execute(); 
$row = $stmnt ->fetchAll(); 
$my_template = new Smarty; 
$my_template->debugging = false; 
$my_template->caching = true; 
$my_template->cache_lifetime = 120; 
$my_template->setTemplateDir('./templates/’'); 
$my_template->assign("row", $row); 
$my_template->display('posts.tpl'); 

//in my smartyposts.tpl 
{foreach $row as $r}  
//display posts here 
{/foreach} 

post_title에서 URL을 생성하는 PHP 함수를 사용하고 싶습니다. 그래서 정상적으로 PHP에서 무엇을합니까

<?php 
     foreach($row as $r){ 
     $post_title = $r[‘post_title’]; 
     $create_link = preg_replace("![^a-z0-9]+!i", "-", $post_title); 
      $create_link = urlencode($create_link); 
      $create_link = strtolower($create_link); 
     ?> 

    <a href="posts/<?php echo $create_link;?>”><?php echo $post_title ;?></a> 
    <?php } ?> 

똑같은 출력을 smarty로 어떻게 얻을 수 있습니까? 나는 어디에서나 검색을했지만 아무런 답을 찾지 못했습니다. 시간을 내 주셔서 감사합니다.

답변

1

만들기 modifier :

test.php

<?php 
require_once('path/to/libs/Smarty.class.php'); 

function smarty_modifier_my_link($title) { 
    $link = preg_replace("![^a-z0-9]+!i", "-", $title); 
    $link = urlencode($link); 
    return strtolower($link); 
} 


$smarty = new Smarty(); 

$smarty->setTemplateDir(__DIR__ . '/templates/'); 
$smarty->setCompileDir(__DIR__ . '/templates_c/'); 
$smarty->setConfigDir(__DIR__ . '/configs/'); 
$smarty->setCacheDir(__DIR__ . '/cache/'); 

$smarty->registerPlugin('modifier', 'my_link', 'smarty_modifier_my_link'); 

$smarty->assign('posts', [ 
    ['post_title' => 'Some Title 1'], 
    ['post_title' => 'Some Title 2'], 
]); 

$smarty->display('index.tpl'); 

템플릿/한편, index.tpl

{foreach $posts as $p} 
<a href="/posts/{$p.post_title|my_link}">{$p.post_title|htmlspecialchars}</a> 
{/foreach} 

출력

<a href="/posts/some-title-1">Some Title 1</a> 
<a href="/posts/some-title-2">Some Title 2</a> 
+0

감사합니다. 매력처럼 작동합니다. – Jordyn