在smarty中加入自定义的常量格式的方法 .

Smarty is a good templating system. In my experience it lacks a bit of customizability, but so far I have been able to hold back on the urge of hacking it to do what I want.

Specifically, I wanted to be able to use constants. The default syntax for using constants in Smarty is:

Code: ( PHP Smarty)

{$smarty.const.YOUR_DEFINE_HERE}

And my preferred version would be:

Code: ( Custom Smarty)

__APP_NAME__
It's shorter, less bloated and thus easier to read. This is not easy to make, yet not impossible to accomplish. Let me show you how to do it in Smarty2:

There are a few ways to plug into the Smarty system. Ideally I would've liked a way to convert just the smart interpreted parts of the template and convert my own syntax to the Smarty compatible one (replacing __APP_NAME__ by {$smarty.const.LANG_SUBMIT} and being done with it). This is not possible. However, you are able to plug into the precompiling "event". You can add your own functions and you can do some other stuff that, eventually, was useless in this case.

I start with a precompiled function to replace the # into a custom function I define later. The custom function simply takes one argument and returns the value of the defined constant (at runtime, that way I can still change the language constant in the database without having to recompile all the Smarty templates).

First the prefilter function:

Code: ( PHP)

//在smarty中直接使用常量的扩展函数 preFilterConstants
function preFilterConstants($strInput, $smarty)
{//在
 $str=  preg_replace("/__(.*)__/",'<{$smarty.const.\\1}>' , $strInput);
 return $str;
Make sure to replace '{' by whatever character you use (I use the backtick ` in my code because curly braces tend to screw stuff up).

And the custom function:

Code: ( PHP)

//在smarty中直接使用常量的扩展函数 functionHash
function functionHash($args, $objSmarty=false)

 $c = $args['c']; 
 if (defined($c)) return constant($c); // 如果常量已定义则抛出异常
 return $c; // 默认的行为
}

Hook it up to the Smarty system:

Code: ( PHP)

$objSmarty->register_prefilter('preFilterConstants');

$objSmarty->register_function('constant', 'functionHash');

And you're done! Your Smarty object can now parse __APP_NAME__ properly. Note that you incur some overhead because of the limitations Smarty imposes with these hacks. The only caveat is that all the instances of {# will be translated, but there won't be many of those in most templates :)

I would like to see an easier way of plugging into Smarty. Surely it's not that difficult of allowing easy access when you already have the parsing system in place?

Maybe Smarty3 will make it easier. Alas I don't have the time to wait for that to finalize in my current project.

Hope it helps you!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值