Smarty

Was ist Smarty

Smarty ist eine Template-Engine für PHP. smarty.net

Smarty Schnipsel

Kommentar

	{* Kommentar *}

if else

	{if $myVar == 'Yes'}...{else}...{/if}

Vergleichsoperatoren

	==
	===
	!=
	>
	>=
	%
	is even
	is not even
	eq

mindestens ein Element

	{if $elements|@count gt 0}...{/if}

Array iterieren mit foreach

	{foreach from=$passesData item=pass key=key}
		value: {$pass.value1}
	{/foreach}

abwechselnd etwas anderes ausgeben mit cycle

	{cycle values="odd, even"}

section zum Hochzählen/Iterieren

	{section name=starLoop start=0 loop=$elem.stars step=1}
		<img class="stars" src="star.png" title="{$elem.stars} {$lang.stars}" alt="{$elem.stars} {$lang.stars}" />
	{/section}

kürzen mit truncate

	{$text|truncate:20}
	{$text|truncate:20:'..':false:false}

Formatierung und Ersetzung

	{$store.km|string_format:"%.2f"|replace:".":","}

===Datumsformatierung=
	{$yesterday|date_format:"%d.%m.%Y"}

nicht parsen/auswerten

	{literal}
		/* Inhalt dazwischen mit geschweiften Klammern { */
		<script type="text/javascript">
			function test() {
				alert('javascript');
			}
		</script>
	{/literal}

Mathematische Operation

	{math equation="x + y" x=$height y=$width}

neue Variable in smarty zuweisen

	{assign var='myName' value=$var.subvar}

Kategorie ausgeben, falls neue Kategorie beginnt

	{assign var='category' value=''}
	{foreach from=$elements item=element}
		{* headline of elements *}
		{if $category != $element.category}
			{assign var='category' value=$element.category}
			<h2>{$category}</h2>
		{/if}
		{* elements *}
		<div>{element.value}</div>
	{/foreach}

Datei einbinden

	{foreach from=$arrProducts item=product key=index name=foo}
		{if $view == 1}
			{include file="view1.tpl" fooIndex=$smarty.foreach.foo.index}
		{else}
			{include file="view2.tpl" fooIndex=$smarty.foreach.foo.index}
		{/if}
	{foreachelse}

Wiki-Datei des Artikels herunterladen