在 smarty 中创建一个函数来解析名称的最佳方法是什么?
例:我有变量 {$attachment.文件名}
如果文件名为 .jpg|。JPEG|.动图|..png---我的结果---(在灯箱中打开的选项...否则没有在灯箱中打开的选项...
谢谢!
在 PHP 中进行解析并在 Smarty 变量中设置一个标志。在模板中检查标志并显示您需要的内容。不要在模板中嵌入逻辑。
如果您确实需要许多模板中的此功能,您确实可以编写适合您需求的 Smarty 插件。
有关 Smarty 插件的文档包括可以激发您灵感的示例。
例如:
// Define the function that implements the plugin
function my_special_img($params, Smarty_Internal_Template $template)
{
$src = $params['src'];
// Based on $src decide here if you want lightbox or not
$lightbox = TRUE; // or FALSE
// Generate the <img> element
// Get information from $params, put default values, do whatever you want
$output = implode(' ', array( // build the string from pieces
'<img',
'src="{$src}"',
'width="{$params['width']}"',
'height="{$params['height']"',
'alt="{$params['alt']}"',
'class="{$params['class']}"',
($lightbox ? 'rel="lightbox"' : ''),
'/>'
));
// Smarty will replace the function call in the template with the value it returns
return $output;
}
// Register the plugin in Smarty
$smarty->registerPlugin('function', 'image', 'my_special_img');
在模板中,替换
<img src="filename.jpg" width="40" alt="bla-bla" etc>
跟
{image src="filename.jpg" width="40" alt="bla-bla" etc}
就这样。在插件的代码中表达您的创造力,但保持简单,仅使用 $params
中提供的值。