简体   繁体   English

在PHP模板系统中实现条件的最佳方法?

[英]Best way to implement conditional in a PHP templating system?

I'm creating a very simple PHP templating system for a custom CMS/news system. 我正在为自定义CMS /新闻系统创建一个非常简单的PHP模板系统。 Each article has the intro and the full content (if applicable). 每篇文章都有介绍和完整内容(如果适用)。 I want to have a conditional of the form: 我想要一个条件形式:

{continue}click to continue{/continue}

So if it's possible to continue, the text "click to continue" will display, otherwise, don't display this whole string. 因此,如果可以继续,将显示文本“单击以继续”,否则,请勿显示整个字符串。 So far, it works like this: if we can continue, remove the {continue} tags; 到目前为止,它是这样工作的:如果可以继续,请删除{continue}标签; otherwise, remove the whole thing. 否则,请删除整个内容。

I'm currently using preg_match_all to match the string in the second case. 我目前正在使用preg_match_all在第二种情况下匹配字符串。 What is the best function for removing the matched text? 删除匹配文本的最佳功能是什么? A simple str_replace , or something else? 一个简单的str_replace还是其他?

Or is there a better way to implement this overall? 还是有更好的方法来实现这一目标?

Why not use preg_replace_callback ? 为什么不使用preg_replace_callback

Specifically: 特别:

preg_replace_callback('!\{continue\}(.*)\{/continue\}!Us', 'replace_continue', $html);

function replace_continue($matches) {
  if (/* can continue */) {
    return $matches[1];
  } else {
    return '';
  }
}

I find preg_replace_callback to be incredibly useful. 我发现preg_replace_callback非常有用。

Sorry I know people have been ridiculing this kind of answer, but just use Smarty. 抱歉,我知道人们一直在嘲笑这种答案,但是请使用Smarty。 Its simple, stable, clever, free, small and cheap. 它简单,稳定,聪明,免费,小巧而廉价。 Spend an hour learning how to use it and you will never look back. 花一个小时学习如何使用它,您将永远不会回头。

Go to www.smarty.net 前往www.smarty.net

For PHP templating systems the proper way is to parse the template (using state machine or at least preg_split ), generate PHP code from it, and then use that PHP code only. 对于PHP模板系统,正确的方法是解析模板(使用状态机或至少使用preg_split ),从模板生成PHP代码,然后仅使用该PHP代码。 Then you'll be able to use normal if for conditional expressions. 然后, if条件表达式可以使用normal。

Regular expressions aren't good idea for implementing templates. 正则表达式不是实现模板的好主意。 It will be PITA to handle nesting and enforce proper syntax beyond basic cases. 在基本情况之外,将由PITA处理嵌套并执行适当的语法。 Performance will be very poor (you have to be careful not to create backtracking expression and even then you'll end up scanning and copying KBs of templates several times). 性能将非常差(您必须注意不要创建回溯表达式,即使那样,您最终也会多次扫描和复制模板的KB)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM