English فارسی Suomi
Français Nederlands Translate

Campsite 3.4

Campsite: BasicSyntax

Basic Syntax

In this article:
  • Comments
  • Variables
  • Functions
  • Attributes
  • Embedding Vars in Double Quotes
  • Math
  • Escaping Smarty Parsing
  • Modifiers

The Campsite template engine was built upon Smarty so the Campsite template language is actually an extension of the Smarty template language. For details on the Smarty template language please go to this link: http://smarty.net/manual/en/smarty.for.designers.php

All template tags are enclosed within delimiters. By default these are { and }, but they can be changed. In Campsite we use {{ and }}.

For the examples in this manual, we will assume that you are using the default Campsite delimiters. All content outside of delimiters is displayed as static content, or unchanged. When the template engine encounters template tags, it attempts to interpret them, and displays the appropriate output in their place.

The following sub-chapters, which were copied from the Smarty manual, will familiarize you with the Smarty syntax.


Comments

Template comments are surrounded by asterisks, and that is surrounded by the delimiter tags like so:

{{* this is a comment *}}

Comments are NOT displayed in the final output of the template, unlike <!-- HTML comments -->. These are useful for making internal notes in the templates which no one will see ;-)

Example 3-1. Comments within a template

{{* I am a template comment, I don't exist in the compiled output  *}}
<html>
<head>
<title>{{$title}}</title>
</head>
<body>

{{* another single line comment  *}}
<!-- HTML comment that is sent to the browser -->

{{* this multiline
   comment is
   not sent to browser
*}}

{{*********************************************************
Multi line comment block with credits block
  @ author:         bg@example.com
  @ maintainer:     support@example.com
  @ para:           var that sets block style
  @ css:            the style output
**********************************************************}}

{{* The header file with the main logo and stuff  *}}
{{include file='header.tpl'}}


{{* Dev note:  the $includeFile var is assigned in foo.php script  *}}
<!-- Displays main content block -->
{{include file=$includeFile}}

{{* this <select> block is redundant *}}
{{*
<select name="company">
  {{html_options options=$vals selected=$selected_id}}
</select>
*}}

<!-- Show header from affiliate is disabled -->
{{* $affiliate|upper *}}

{{* you cannot nest comments *}}
{{*
<select name="company">
  {{* <option value="0">-- none -- </option> *}}
  {{html_options options=$vals selected=$selected_id}}
</select>
*}}


{{* cvs tag for a template, below the 36 SHOULD be an american currency
. however its converted in cvs.. *}}
{{* &#36;Id: Exp &#36; *}}
{{* $Id: *}}
</body>
</html>

 

Variables

Template variables start with the $dollar sign. They can contain numbers, letters and underscores, much like a PHP variable. You can reference arrays by index numerically or non-numerically. Also reference object properties and methods.

Config file variables are an exception to the $dollar syntax and are instead referenced with surrounding #hashmarks#, or via the $smarty.config variable.

Example 3-2. Variables

{{$foo}}        <-- displaying a simple variable (non array/object)
{{$foo[4]}}     <-- display the 5th element of a zero-indexed array
{{$foo.bar}}    <-- display the "bar" key value of an array, similar to PHP $foo['bar']
{{$foo.$bar}}   <-- display variable key value of an array, similar to PHP $foo[$bar]
{{$foo->bar}}   <-- display the object property "bar"
{{$foo->bar()}} <-- display the return value of object method "bar"
{{#foo#}}       <-- display the config file variable "foo"
{{$smarty.config.foo}} <-- synonym for {{#foo#}}
{{$foo[bar]}}   <-- syntax only valid in a section loop, see {{section}}
{{assign var=foo value='baa'}}{{$foo}} <--  displays "baa", see {{assign}}

Many other combinations are allowed

{{$foo.bar.baz}}
{{$foo.$bar.$baz}}
{{$foo[4].baz}}
{{$foo[4].$baz}}
{{$foo.bar.baz[4]}}
{{$foo->bar($baz,2,$bar)}} <-- passing parameters
{{"foo"}}       <-- static values are allowed

{{* display the server variable "SERVER_NAME" ($_SERVER['SERVER_NAME'])*}}
{{$smarty.server.SERVER_NAME}}

Request variables such as $_GET, $_SESSION, etc are available via the reserved $smarty variable.

See also $smarty, config variables {{assign}} and assign().

 

Functions

Every Smarty tag either prints a variable or invokes some sort of function. These are processed and displayed by enclosing the function and its attributes within delimiters like so: {{funcname attr1='val1' attr2='val2'}}.

Example 3-3. function syntax

{{config_load file='colors.conf'}}

{{include file='header.tpl'}}
{{insert file='banner_ads.tpl' title='Smarty is cool'}}

{{if $logged_in}}
    Welcome, <font color="{{#fontColor#}}">{{$name}}!</font>
{{else}}
    hi, {{$name}}
{{/if}}

{{include file='footer.tpl' ad=$random_id}}

See also register_function()

 

Attributes

Most of the functions take attributes that specify or modify their behavior. Attributes to Smarty functions are much like HTML attributes. Static values don't have to be enclosed in quotes, but it is recommended for literal strings. Variables may also be used, and should not be in quotes.

Some attributes require boolean values (TRUE or FALSE). These can be specified as either unquoted true, on, and yes, or false, off, and no.

Example 3-4. function attribute syntax

{{include file='header.tpl'}}

{{include file='header.tpl' attrib_name='attrib value'}}

{{include file=$includeFile}}

{{include file=#includeFile# title='Smarty is cool'}}

{{html_select_date display_days=yes}}

{{mailto address='smarty@example.com'}}

<select name='company_id'>
  {{html_options options=$companies selected=$company_id}}
</select>

 

Embedding Vars in Double Quotes

  • Smarty will recognize assigned variables embedded in "double quotes" so long as the variable name contains only numbers, letters, under_scores and brackets[]. See naming for more detail.

  • With any other characters, for example a .period or $object>reference, then the variable must be surrounded by `backticks`.

  • You cannot embed modifiers, they must always be applied outside of quotes.

Example 3-5. Syntax examples

{{func var="test $foo test"}}       <-- sees $foo
{{func var="test $foo_bar test"}}   <-- sees $foo_bar
{{func var="test $foo[0] test"}}    <-- sees $foo[0]
{{func var="test $foo[bar] test"}}  <-- sees $foo[bar]
{{func var="test $foo.bar test"}}   <-- sees $foo (not $foo.bar)
{{func var="test `$foo.bar` test"}} <-- sees $foo.bar
{{func var="test `$foo.bar` test"|escape}} <-- modifiers outside quotes!

Example 3-6. Practical examples

{{* will replace $tpl_name with value *}}
{{include file="subdir/$tpl_name.tpl"}}

{{* doesn't replace $tpl_name *}}
{{include file='subdir/$tpl_name.tpl'}} <--

{{* must have backticks as it contains a . *}}
{{cycle values="one,two,`$smarty.config.myval`"}}

{{*  same as $module['contact'].'.tpl' in a php script *}}
{{include file="`$module.contact`.tpl"}}

{{*  same as $module[$view].'.tpl' in a php script *}}
{{include file="$module.$view.tpl"}}
See also escape

 

Math

Math can be applied directly to variable values.

Example 3-7. math examples

{{$foo+1}}

{{$foo*$bar}}

{{* some more complicated examples *}}

{{$foo->bar-$bar[1]*$baz->foo->bar()-3*7}}

{{if ($foo+$bar.test%$baz*134232+10+$b+10)}}

{{$foo|truncate:"`$fooTruncCount/$barTruncFactor-1`"}}

{{assign var="foo" value="`$foo+$bar`"}}

See also the {{math}} function for complex equations and {{eval}}.

 

Escaping Smarty Parsing

It is sometimes desirable or even necessary to have Smarty ignore sections it would otherwise parse. A classic example is embedding Javascript or CSS code in a template. The problem arises as those languages use the { and } characters which are also the default delimiters for Smarty.

The simplest thing is to avoid the situation altogether by separating your Javascript and CSS code into their own files and then using standard HTML methods to access them.

Including literal content is possible using {{literal}}..{{/literal}} blocks. Similar to HTML entity usage, you can use {{ldelim}},{{rdelim}} or {{$smarty.ldelim}} to display the current delimiters.

 

Modifiers

Modifiers can be applied to variables, custom functions or strings. To apply a modifier, specify the value followed by a | (pipe) and the modifier name. A modifier may accept additional parameters that affect its behavior. These parameters follow the modifer name and are separated by a : (colon). Also, all php-functions can be used as modifiers implicitly (more below) and modifiers can be combined.

Example 5-1. Modifier examples

{* apply modifier to a variable *}
{$title|upper}

{* modifier with parameters *}
{$title|truncate:40:'...'}

{* apply modifier to a function parameter *}
{html_table loop=$myvar|upper}

{* with parameters *}
{html_table loop=$myvar|truncate:40:'...'}

{* apply modifier to literal string *}
{'foobar'|upper}

{* using date_format to format the current date *}
{$smarty.now|date_format:"%Y/%m/%d"}

{* apply modifier to a custom function *}
{mailto|upper address='smarty@example.com'}

{* using  php's str_repeat *}
{'='|str_repeat:80}

{* php's count *}
{$myArray|@count}

{* php's shuffle on servers's ip *}
{$smarty.server.SERVER_ADDR|shuffle}

(* this will uppercase and truncate the whole array *}
<select name="name_id">
{html_options output=$myArray|upper|truncate:20}
</select>
  • If you apply a modifier to an array variable instead of a single value variable, the modifier will be applied to every value in that array. If you really want the modifier to work on an entire array as a value, you must prepend the modifier name with a @ symbol.

    Example:{$articleTitle|@count} - will print out the number of elements in the $articleTitle array using the php count() function as a modifier.

  • Modifiers are autoloaded from the $plugins_dir or can be registered explicitly with the register_modifier() function. The later is useful for sharing a function between php scripts and smarty templates.

  • All php-functions can be used as modifiers implicitly, as demonstrated in the example above. However, using php-functions as modifiers has two little pitfalls:

    • First - sometimes the order of the function-parameters is not the desirable one. Formatting $foo with {"%2.f"|sprintf:$foo} actually works, but asks for the more intuitive, like {$foo|string_format:"%2.f"} that is provided by the Smarty distribution.

    • Secondly - if $security is enabled, all php-functions that are to be used as modifiers have to be declared trusted in the MODIFIER_FUNCS element of the $security_settings array

You can apply any number of modifiers to a variable. They will be applied in the order they are combined, from left to right. They must be separated with a | (pipe) character:
{$articleTitle}
{$articleTitle|upper|spacify}
{$articleTitle|lower|spacify|truncate}
{$articleTitle|lower|truncate:30|spacify}
{$articleTitle|lower|spacify|truncate:30:". . ."}

 


EDIT