Forums / Cotonti / Core Labs / Archive / XTemplate 2.0

12>>>

Brand new minimalistic implementation

Trustmaster
#1 2009-07-11 19:47
When we played with XTemplate, we discovered that its code is quite messy and inefficient. We thought of probably rewriting it but at a very low priority. But a bit of spare time and an important security flaw I found in previous XTemplate implementation (PHP injection in logical statements) encouraged me to write a brand new implementation of XTemplate from scratch.

It is almost backwards compatible with original XTemplate, but it only implements those features that we use in Cotonti. This principle is called minimalistic. Here is what it supports:
  • Blocks and original XTemplate flow control
  • Variable substitutions (aka tags)
  • Logical blocks (if/else/endif)
  • Inclusion of other templates within templates with FILE
Here is what it does not support:
  • Callbacks
  • Customizable syntax

Another principle is strict. It means that:
  • Statements are case sensitive. It will understand BEGIN but not begin:
    <!-- BEGIN: TEST -->
        <div>This is a valid block!</div>
    <!-- END: TEST -->
    
    <!-- begin: test -->
        <div>This block is invalid!</div>
    <!-- end: test -->
    
  • Spaces matter, especially in logical statements. There must be spaces in statements at correct positions, e.g.
    <!-- IF {PHP.something} > 0 -->
        <div>This is a valid block!</div>
    <!-- ENDIF -->
    
    <!--IF{PHP.something}>0-->
        <div>This block is invalid!</div>
    <!--ENDIF-->
    
  • Logical expressions are limited functionality. Supported logical operators are: AND, OR (AND has higher priority). Parenthesis is not supported. Supported comparison operators are: ==, !=, <, >, <=, >=, !. First operand of comparison must be a template variable e.g. {PHP.my.test}. Second operand may be a template variable, a number or a quoted string. Example:
    <!-- IF {USER_DETAILS_NAME} = 'Mark' AND {PHP.g} >= 6 OR !{PHP.error_string} -->
        <div>The expression is true!</div>
    <!-- ELSE -->
        <div>The expression is false!</div>
    <!--END:TEST-->
    
  • Nested logical blocks are not supported, e.g.
    <!-- IF {PHP.foo} = 'test' -->
        <!-- IF {PHP.bar} -->
            <div>This block is invalid!</div>
        <!-- ENDIF -->
    <!-- ENDIF -->
    
  • Template blocks inside of logical blocks are not supported, e.g.
    <!-- IF {PHP.foo} = 'test' -->
        <!-- BEGIN: BAR -->
            <div>This block is invalid!</div>
        <!-- END: BAR -->
    <!-- ENDIF -->
    

The third principle is fast. XTemplate 2.0 is much faster than original XTemplate 1.0, literally 2 times faster. Benchmarks demonstrate 5-35% RPS (requests per second) increase for entire pages after upgrade.

The fourth principle is lightweight. The code is 4 times smaller.

What's new in XTemplate 2.1:
  1. Block names are no more space sensitive, so it's compatible with XTemplate 1.0
  2. Support for {FILE "path/to/template.tpl"}
  3. Disk cache for better performance
May the Source be with you!

Dit bericht is bewerkt door Trustmaster (2009-08-02 15:18, 14 jaren ago)
tensh
#2 2009-07-11 19:57
Great news! :-X
By the way, does it mean that a previous Xtemplate didn't use strict syntax and allowed for various space and case-insensitive statements?
Trustmaster
#3 2009-07-12 00:42
Sorry for misleading: XTemplate 1.0 is sensitive to case and spaces too. I just wanted to list these rules here.
May the Source be with you!
tensh
#4 2009-07-12 18:21
That's good, I was worried if I'll have to check my templates for non-strict tags :)
For testers, be sure to have all tpl files saved in ANSI coding, in case of UTF-8 Xtemplate 2.0 might act differently because of UTF-8 BOM mark at the beginning of a file (Sometimes I'm careless and accidently save tpls as UTF-8).
GHengeveld
#5 2009-07-12 18:55
Great to have logic blocks support while reducing load times!
Trustmaster
#6 2009-07-12 23:52
Hmm, we really need to support UTF-8 templates. Normally UTF-8 files are without BOM but we need to have it served somehow too.

UPDATE:
  • Added BOM removal for UTF-8 with BOM
  • Added variable negation in logic blocks
  • Added support for multi-block TPL files (with multiple root blocks)

And found that XTemplate 1.0 was not space sensitive, so be careful.
May the Source be with you!

Dit bericht is bewerkt door Trustmaster (2009-07-13 01:33, 14 jaren ago)
SunChase
#7 2009-07-13 03:03
Great
I had a problem using the previos XTemplate:
When i put an Extrafield in "If the field isnt empty - show" and entered in that field a link
,in started to give an error on <a href="...">.

The second problem was with the ICQ field in the user.details.It started to work only after i put in the "If" the direct name of the field(not stationar tag)

Have this things been fixed in this version?
[url=http://ka13.orgfree.com]KA13[/url] - The essence of creativity
Trustmaster
#8 2009-07-13 06:36
I haven't quite understood what you were doing.
May the Source be with you!
SunChase
#9 2009-07-13 08:21
Бррр.Хромает формулировка мысли на инглише.Говорю что возникла проблема,когда я сделал так:
Вставил в тпл стандартный
<!-- IF {PHP.urr.user_extra5} !='' -->
в середине которого должно было выводится значение этого поля если оно заполнено.
По задумке в него должна была вписыватся ссылка формата <a href="">... .Предыдущий ХТемплейт что у меня стоял,как в результате длительных поисков выяснилось ,что он выдавал ошибку конкретно изза ковычек (" ") после href=.

Вторая проблема состояла в том,что ХТемплейт реагировал на тег USERS_DETAILS_ICQ (Показывает в page.details номер аськи + значёк\кнопку на веб профиль на самом сайте айсикью).Ошибка аналогичная той,что и в первом случае.

Сама ошибка в обоих случаях писала какойто эрор под шапкой(уже непомню какой - кустарными методами пришлось решать проблему) и вообще невыводило то что должно было выводить по условию.
[url=http://ka13.orgfree.com]KA13[/url] - The essence of creativity
Trustmaster
#10 2009-07-13 13:23
Seems like this problem was connected with eval(). So there will be no such problem. But please take care of spaces in IF expressions:
<!-- IF {PHP.urr.user_extra5} != '' -->
May the Source be with you!
tensh
#11 2009-07-13 15:05
I sniffed that indexpolls plugin contains space-insensitive tags - a lot of them :-)

Correct tpl:

<!-- BEGIN: POLL_VIEW -->
{POLL_FORM_BEGIN}
<table>
<!-- BEGIN: POLLTABLE -->
<tr>
	<td><label>{POLL_INPUT}{POLL_OPTIONS}</label></td>
</tr>
<!-- END: POLLTABLE -->
<tr>
	<td>{POLL_FORM_BUTTON}</td>
</tr>
</table>
{POLL_FORM_END}
<!-- END: POLL_VIEW -->


<!-- BEGIN: POLL_VIEW_VOTED -->
<table style="width:100%;">
<!-- BEGIN: POLLTABLE -->
<tr>
	<td>{POLL_OPTIONS}</td>
	<td align="right">{POLL_PER}% ({POLL_COUNT})</td>
</tr>
<tr>
	<td colspan="2" align="right">
		<div style="width:180px; ">
			<div class="bar_back">
				<div class="bar_front" id="pr_{POLL_PER}"></div>
			</div>
		</div>
	</td>
</tr>
<!-- END: POLLTABLE -->
</table>
<script type="text/javascript">
	function anim(){
		$(".bar_front").each(function(){
			var percentage = Math.floor(($(this).attr("id").replace('pr_','')*180)/100)+'px';
			if ($(this).attr("id")!=""){$(this).css({width:"0"}).animate({width: percentage}, "slow");}
			$(this).attr("id","");
		});
	}
	anim();
</script>
<div><div id="pfsBack">{PHP.skinlang.page.Date} {POLL_SINCE_SHORT}</div> {PHP.skinlang.ratings.Votes} {POLL_VOTERS} </div>
<!-- END: POLL_VIEW_VOTED-->


<!-- BEGIN: POLL_VIEW_DISABLED -->
<table>
<!-- BEGIN: POLLTABLE -->
<tr>
	<td>{POLL_OPTIONS}</td>
</tr>
<!-- END: POLLTABLE -->
<tr>
	<td>{PHP.L.rat_registeredonly}</td>
</tr>
</table>
<!-- END: POLL_VIEW_DISABLED -->

<!-- BEGIN: POLL_VIEW_LOCKED -->
<table style="width:100%;">
<!-- BEGIN: POLLTABLE -->
<tr>
	<td>{POLL_OPTIONS}</td>
	<td align="right">{POLL_PER}% ({POLL_COUNT})</td>
</tr>
<tr>
	<td colspan="2" align="right">
		<div style="width:180px; ">
			<div class="bar_back">
				<div class="bar_front" style="width:{POLL_PER}%;"></div>
			</div>
		</div>
	</td>
</tr>
<!-- END: POLLTABLE -->
</table>
<div><div id="pfsBack">{PHP.skinlang.page.Date} {POLL_SINCE_SHORT}</div> {PHP.skinlang.ratings.Votes} {POLL_VOTERS} </div>
<!-- END: POLL_VIEW_LOCKED -->


<!-- BEGIN: INDEXPOLLS -->
<!-- BEGIN: POLL -->
<h5><a href="{IPOLLS_URL}">{IPOLLS_TITLE}</a></h5>
{IPOLLS_FORM}
<div style="text-align: right;">{PHP.skinlang.comments.Comment} {IPOLLS_COMMENTS}</div>
<hr />
<!-- END: POLL -->

<!-- BEGIN: ERROR -->
<div class="error">{IPOLLS_ERROR}</div>
<!-- END: ERROR -->

<p style="text-align: center;">{IPOLLS_ALL}</p>
<!-- END: INDEXPOLLS -->

Edit:
Also, I noticed that " in articles is escaped (\"Administrators\") - is it correct behaviour or should it be exchanged with html equivalent of this sign? (it doesn't have anything to do with X-Template, though)

Dit bericht is bewerkt door tensh (2009-07-13 15:10, 14 jaren ago)
Trustmaster
#12 2009-07-13 15:35
Both are now fixed in trunk, will be available in beta3
May the Source be with you!
tensh
#13 2009-07-13 16:56
In case of very old plugins like "contactus" (which don't containg tags nor even templates), the following error appears during installation:

Warning: mb_strpos() [function.mb-strpos]: Offset not contained in string in /home/sth/site/system/xtemplate.class.php on line 85
Fatal error: Allowed memory size of 67108864 bytes exhausted (tried to allocate 27132033 bytes) in /home/sth/site/system/xtemplate.class.php on line 287

Edit:

Hmm, the same happens in other plugins... now I'm not that sure what might be the cause. Other plugin parts? Or something with ajax?

Edit2:

Xtemplate sometimes acts unstable... like it displays the beginning of page.tpl like this:
<!-<div class="mboxHD"><a href="news/">News</a>
It's because it doesn't accept foreign letters in ANSI coding as well.
Also, BOM-removing code doesn't work, header.tpl with BOM mark is not loaded at all.
UTF-8 tpls without BOM are displayed correctly. The same with ANSI coded tpl without special letters.

Dit bericht is bewerkt door tensh (2009-07-13 18:49, 14 jaren ago)
Trustmaster
#14 2009-07-13 21:24
admin.plug.inc.tpl causes that, not the plugins. It will be fixed today.

Could you give those templates with BOM to test?
May the Source be with you!
tensh
#15 2009-07-13 22:46
Ok, here's header.tpl with BOM:
http://www.yot.nazwa.pl/header.zip

12>>>