Smarty and PHP syntax in one document - recommended?
I'm creating a website using Smarty and PHP syntax; I've learnt PHP code can be used in Smarty at http://www.smarty.net/docs/en/language.function开发者_运维知识库.php.tpl
However, is this a good idea - mixing Smarty syntax with PHP coding?
I'm still editing the document so no code as yet; all advice appreciated.
I would not mix those two syntaxes : either use your templating engine, or don't use one... But don't mix both!
One of the goals of a templating engine is for html-guys to learn it, and not PHP -- if you mix both, well, fail for that goal.
If you want to use PHP in your templates, you can just PHP as a templating engine, afterall :-)
The important thing (no matter if you use PHP or smarty or whatever other possible templating engine) is to remember that views (templates, in your case) are for presentation, and not logic.
You generally should try and do all of your server side work in a PHP file and assign output to be used later on in a template file. It's best to de-couple business and presentation logic and keep them each in their own respective areas.
Smarty displays the data that has been built by PHP. If you want flexible designs, anythings that is strictly related to the displaying of values/object should be in the template. So if you change how things are displayed PHP doesn't do unnecessary calculations. So, to summarize, moving display related things to the PHP code is a bad idea.
The good news is that there are ways to not include raw PHP code in templates. You can build custom functions, modifiers or even controls specifically designed for various tasks. If it makes sense (seems reusable) you can also pass objects which do display related functions.
Update: note that this answer differs from the other ones, it doesn't suggest to move those functions to PHP. Only do that, if it has nothing to do with the displaying of the data, and has to be done no matter how you structure your layout and what representation you choose displaying your data.
No, it's not a good idea. Smarty itself doesn't give a damn - it compiles the templates to PHP anyway - but you will be pulling your hair out, as your pages will become a mess of write-only spaghetti code. (been there, done that)
Smarty exists to abstract your templates away from your PHP code, so you can keep them somewhat separated. If you insist on mixing them up again - well, might as well code in raw PHP, right? (hint: that's an Even Worse Idea)
No, it isn't a good idea. The goal of the smarty template is to let someone who doesn't understand php update the markup easily without having to learn php itself. So in that vein, if you feel the need to add php code to the template you should ask yourself if it absolutely has to be in the template and can't be place in the logic feeding into the template.
Keep the business logic and display seperate.
精彩评论