如何在Smarty中使用PHP函数集

开发技术 作者: 2024-06-28 21:55:01
我真的很聪明.我想知道如何在smarty中使用一组 PHP函数.我知道有些功能可以直接使用. 例如:{$my_string | strip_tags} 我正在使用PDO和smarty.请在下面的代码中查看我的帖子 $stmnt = $conn->prepare("SELECT post_id, post_title FROM posts ORDER BY post_id DESC"); $stmn
我真的很聪明.我想知道如何在smarty中使用一组 PHP函数.我知道有些功能可以直接使用.

例如:{$my_string | strip_tags}

我正在使用PDO和smarty.请在下面的代码中查看我的帖子

$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}

我想使用一些PHP函数从post_title创建url.通常我在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实现相同的输出?我到处搜索但找不到任何答案.感谢你的时间.

解决方法

创建一个 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>
原创声明
本站部分文章基于互联网的整理,我们会把真正“有用/优质”的文章整理提供给各位开发者。本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
本文链接:http://www.jiecseo.com/news/show_35210.html
如何 smarty 使用 php 函数