AGK ([info]kucheryavenko) wrote in [info]ru_php,

Templating Engines in PHP


Автор Symfony MVC framework - Fabien Potencier
опубликовал пост, в котором анализирует Templating Engines in PHP и представляет новый Template engine - Twig.

Wiki - Template_engine_(web)#Comparison

  • Post a new comment

    Error

    Anonymous comments are disabled in this journal

    Your reply will be screened

    Your IP address will be recorded 

  • 37 comments

[info]slonik_v_domene

October 8 2009, 10:21:25 UTC 2 years ago

Smarty номер 2? Зачем?

[info]boba_keyost

October 8 2009, 10:54:22 UTC 2 years ago

Общая тенденция.
Сейчас новая волна велосипедописания(посмотрите рынок браузеров, особенно японцев).

[info]slonik_v_domene

October 8 2009, 11:10:24 UTC 2 years ago

Я ничего прости велосипедов не имею, сам грешен.

Проблема только в том, что новый велосипед должен быть хоть в сем-то лучше сушествующих, и отличаться не только именем автора. Беглый анализ показывает что это те же яйца только в профиль по сравнению со Smarty.

[info]boba_keyost

October 8 2009, 11:19:33 UTC 2 years ago

А кто же не писал в свой жизни велосипедов. Все мы такие.
А по поводу этого шаблонизатора вцелом согласен.
>Беглый анализ показывает что это те же яйца только в профиль
+100.

Может тут какая-то более навороченная система с арифметикой(как я считаю - очень слабая сторона смарти).

[info]kucheryavenko

October 8 2009, 10:58:17 UTC 2 years ago

А статью не читали? :)

привожу читаты ...

As PHP have a million template engines, I have only tested and benchmarked the more "popular" ones. And as I don't use these libraries, the following sections can contain wrong information. In such a case, please correct me in the comments and I will then fix this post accordingly.

Ниже в статье бенчмарки.

по Smarty...
But Smarty suffers from several problems:

* Not object oriented
* No template inheritance
* No sandbox mode
* No automatic escaping

As far I understand, Smarty 3 is just around the corner and will improve the library quite a lot:

* Object oriented architecture
* Auto escaping of variables
* Template inheritance

I tested the two versions, but the performance of both are quite bad (see at the end of this post for more information on the benchmark I did).

[info]slonik_v_domene

October 8 2009, 11:07:46 UTC 2 years ago

Re: А статью не читали? :)

Когда кто-то начинает городить object oriented и template inheritance, это 100% говорит о неизлечимом заболевании - ООП головного мозга.

Подпускать таких людей к шаблонам преступно.

[info]kucheryavenko

October 8 2009, 11:17:20 UTC 2 years ago

Re: А статью не читали? :)

ладно. хорошо, про ООП умолчу... :) меня самого это особо не интересовало в Templating Engines и в статье в частности.

На вот это что скажете?

For me, security should be enabled by default, especially for templates written by non-developers who are not necessarily aware of the common web threats like XSS or CSRF.

As far as I know, symfony was one of the very first web frameworks to have automatic output escaping for variables used in templates (2006); and in the recent years, major frameworks followed the same path: Django has automatic output escaping enabled since 1.0, and Ruby on Rails will also have it in the upcoming version 3.

И по бенчмаркам интересно мнение.

[info]slonik_v_domene

October 8 2009, 11:30:28 UTC 2 years ago

Re: А статью не читали? :)

> For me, security should be enabled by default,

Круто, но какая именно securty?
Для HTML? Для XML? Для WML?
Нельзя сделать универсальное решение, а сделав только default enabled HTML escape мы получим букет проблем при генерации XML. И наоборот.

Кроме того, автоматический escape все равно не решает всех проблем с XSS, но при этом снижает скорость работы шаблонизатора. Классическая палка о двух концах, к сожалению.

[info]graymur

October 8 2009, 12:11:03 UTC 2 years ago

The PHP language is verbose. You need no less than 14 characters just to output a simple variable (and no, using the more compact
Почему?

[info]kucheryavenko

October 8 2009, 12:21:40 UTC 2 years ago

Почему?

Вы имеет уникальную возможность задать вопрос автору статьи.:)
Ссылка на статью в теме. :)

Аналогичный вопрос был задан уже - Dominic, ответа пока не последовало.
Dominic — October 08, 2009 00:39 #9
Just curious: you mention that "using the more compact )

What are some of the things I'd like to see in a modern templating language? How about familiarity for a huge percentage of developers and designers? How about IDE auto-completion? (I'm really going to miss that.) How about being able to step through templates in a debugger?

И еще автор по этой теме хочет выступать на Zend Conference, и просит проголосовать за его выступление на ней для боле глубокого обсуждения вопроса. :)

This blog post is not for the faint-hearted! Some people will strongly disagree with me and some others will probably want to kill me at the upcoming Zend Conference. And if starting an argument in the comments can help you feel better, please feel free to do so. If you want to have a more advanced discussion on this topic, vote for my talk at the Zend UnConference.

[info]graymur

October 8 2009, 12:24:40 UTC 2 years ago

Re: Почему?

что-то мне кажется, что особых аргументов у него не будет. однако без этого заявления он не смог бы так долго обсуждать, какой пэхепэ "многословный".

[info]kucheryavenko

October 8 2009, 12:44:40 UTC 2 years ago

Re: Почему?

Думаю вы правы. По крайней мере у меня возникали аналогичные вопросы.
Я даже есть вопрос об уместности - Template engine in PHP.
Скорость выполнения снижается, но зато КРАЙНЕ выделено ПРЕДСТАВЛЕНИЕ.
И можно ли считать ПРЕДСТАВЛЕНИЕМ(аля MVC) без template engine, а на чистом пхп. :)

P.S. Еще думаю многие вспомнят про разделение труда программиста и верстальщика. :)

[info]graymur

October 8 2009, 12:56:22 UTC 2 years ago

Re: Почему?

моё мнение - городить огород ради того, чтобы писать не <?=$var?>, а {var} - дурная работа. не думаю, что отличие представления от не представления заключается в синтаксисе вывода переменных.

[info]graymur

2 years ago

[info]bal

2 years ago

[info]kucheryavenko

October 9 2009, 14:00:38 UTC 2 years ago

Ответ...

А вот и его ответ... :)
http://fabien.potencier.org/article/35/templating-engines-in-php-follow-up

Many people seem to like the PHP short tags. First, about the math. If you compare with , the difference is 7 characters, not 2. But that's really not the main problem.

Apart from problems like XML support, the short_open_tag setting, the shared hosts configuration issue, and some more, it's also about coding standards:

*

PEAR:

"Always use to delimit PHP code, not the shorthand. This is required for PEAR compliance and is also the most portable way to include PHP code on differing operating systems and setups."
*

Zend:

"Short tags are never allowed."

The Pear and Zend projects are serious, so there should have some reasons to disallow short tags, no?

But as Eli mentioned in his post, I would also like to see a PHP evolution to take this problem into account: "... there are a number of people (including myself [Eli]), who have been tossing around the idea of proposing a new option to the short_tags directive for PHP, allowing not just having them turned on or off. But allowing a 3rd option, that would enable while disabling "

[info]graymur

October 9 2009, 14:04:28 UTC 2 years ago

Re: Ответ...

The Pear and Zend projects are serious, so there should have some reasons to disallow short tags, no?
Значит, своих причин у него нет.

[info]kucheryavenko

October 9 2009, 14:09:41 UTC 2 years ago

Re: Ответ...

Хотя в коментах есть ссылка на
http://framework.zend.com/manual/en/zend.view.html#zend.view.introduction.shortTags

но все такие это мануал по зенд фреймворку
а в стандарте http://framework.zend.com/manual/en/coding-standard.coding-style.html

Short tags are never allowed. For files containing only PHP code, the closing tag must always be omitted (See ???).

[info]kucheryavenko

October 9 2009, 14:11:43 UTC 2 years ago

Re: Ответ...

вот так вот, сами в зенд не разберутся что и как. :D

[info]bal

October 8 2009, 17:01:12 UTC 2 years ago

Спасибо. Пощупаем, сравним ;)

[info]sb16

October 8 2009, 23:07:11 UTC 2 years ago

НАДО СРОЧНО ПИСАТЬ НОВЫЙ ЯЗЫК ПРОГРАММИРОВАНИЯ НА ТВИГЕ!!! ТВИГ - НАШЕ ВСЁ!!!

[info]zupernintendo

October 9 2009, 19:34:27 UTC 2 years ago

а это забыли проанализировать
http://haxe.org/api/haxe/template

[info]kucheryavenko

October 10 2009, 09:09:01 UTC 2 years ago

0_0

статью прочти, там явно указано что проанализированы основные популярные Template Engines

As PHP have a million template engines, I have only tested and benchmarked the more "popular" ones. And as I don't use these libraries, the following sections can contain wrong information. In such a case, please correct me in the comments and I will then fix this post accordingly.

[info]zupernintendo

October 10 2009, 08:07:22 UTC 2 years ago

{% for user in users %}
  * {{ user.name }}
{% else %}
  No user has been found.
{% endfor %}


И накого расщитан такой синтаксис - на верстальшика? Особых отличий от native php чтото не заметно.
Для верстальшика было бы удобно упрощоные теги шаблонизации, например:
<block attr=1> 
  {var1}
  {bar2}
  <row attr=1> 
    {var4} - {bar3}
  </row> 
</block> 


Реализуется это с помошью preg_replace_callback("pattern", array($generator, "subs"), $template);
Таким образом можно ввести какой угодно вид тегов, а требования для них зачастую различаются.

[info]kucheryavenko

October 10 2009, 09:05:24 UTC 2 years ago

...

а если внимательнее прочитать - то синтаксис из Django Template.

[info]zupernintendo

October 11 2009, 09:55:54 UTC 2 years ago

Re: ...

да хоть руби темплейтс - суть то не меняется - изучение нового диалекта разметки, щитай почти программирование
Create an Account
Forgot your login or password?
Facebook Twitter More login options
English • Español • Deutsch • Русский…