Templates

Contents...

Webasyst framework utilizes Smarty as the default template engine.

Webasyst framework applies no limitations to the development of web design or HTML coding. The single strict requirement is correct location and name of a template file. Read more about naming rules for HTML template files in section "Naming rules and recommendations".

Use of Smarty

To facilitate application development, the framework offers several variables and helpers which are accessible in HTML templates.

Variables

  • {$wa_url}: path to the base framework directory relative to the base website directory.
  • {$wa_app_url}: relative URL of apps's main page. In frontend templates this variable returns the path to the application's main frontend page; in backend templates it returns the path to the application's main backend page respectively.
  • {$wa_app_static_url}: path to the application subdirectory relative to the root website directory (useful for creating hyperlinks to static application files; e.g.: {$wa_app_static_url}img/logo.png.
  • {$wa_app}: returns the application's APP_ID.
  • {$wa_backend_url}: backend's relative URL.

Helper $wa:

  • {$wa->header()} returns HTML code of the backend header containing the list of installed applications and the current user name.
  • {$wa->app()}: application APP_ID.
  • {$wa->appName()}: application name.
  • {$wa->accountName()}: account name (usually displayed in the top-right corner of the backend interface).
  • {$wa->css()} returns HTML code to include default CSS style sheets.
  • {$wa->user()->getName()}: current user name.
  • {$wa->user()->getId()}: current user ID.
  • {$wa->version()}: application version number.
  • {$wa->url()}: path to the framework installation directory relative to the base website directory.
  • {$wa->url(true)}: path to the backend base URL relative to the base website URL.

Localization

In order to display text strings dynamically translated into the current user language, localization syntax provided by gettext extension should be used. To do so, use a localization key inside the [` `] structure; e.g., [`some gettext key`] instead of a text string itself. Read more about the localization handling in section "Localization".

Example

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>{$wa->appName()} &mdash; {$wa->accountName()}</title>
  {$wa->css()}
  <script src="{$wa_url}wa-content/js/jquery/jquery-1.4.2.min.js" type="text/javascript"></script>	
</head>
<body>
  <div id="wa">
    {$wa->header()}
    <div id="wa-app">
      <div class="block">
        {if !$records}
        <p>[`Guestbook is empty. Write a new post on the public guestbook page.`]</p>
        {else}
        <ul class="zebra">
          {foreach from=$records item=r}
          <li>
            {if $rights_delete}<a class="count" href="?action=delete&id={$r.id}"><i class="icon16 delete"></i></a>{/if}
            <span class="hint">
              <strong>{$r.name|escape}</strong>
              {$r.datetime|wa_datetime}
            </span>
            {$r.text|escape|nl2br}						
          </li>
          {/foreach} 
        </ul>
        {/if}
        <a href="{$url}" target="_blank">[`Guestbook on site`]</a>
        <i class="icon10 new-window"></i>
      </div>
    </div>
  </div>
</body>
</html>

Use of other template engines

The default template engine Smarty 3 can be replaced with other alternatives.

The framework interacts with the currently used template engine by means of a special adapter class. Specifically, reference to Smarty 3 occurs via system class waSmarty3View declared in file wa-system/view/waSmarty3View.class.php.

In order to use a different template engine, an adapter class must be created and connected (via the configuration file) to enable interaction between the framework and the template engine.

Using templates written in pure PHP

The framework contains an adapter which allows using ordinary PHP files as page templates.

Note: This simple adapter has been developed for demo purposes and is not supposed to be used in high-load projects.

To make your application utilize pure PHP instead of Smarty, create configuration file wa-apps/{APP_ID}/lib/config/factories.php with the following contents :

<?php

return array(
    'view' => 'waPHPView'
)

If file factories.php already exists in your application directory, simply add the new line to it.

PHP files used as templates must be named according to the same rules as those applied to Smarty template files (read more in section "Naming rules and recommendations"). The only difference between these cases lies in the file name extensions. Unlike Smarty templates with .html extensions, the names of PHP templates have the standard .php extension.

Within PHP templates the same variables and helper $wa are accessible as in Smarty templates.

Creating a custom template engine adapter

Each application can be set up to utilize a template engine convenient for the developer. This is achieved through specifying the name of the adapter class in configuration file wa-apps/{APP_ID}/lib/config/factories.php:

<?php

return array(
    'view' => '{NAME OF THE VIEW ADAPTER CLASS NAME}'
);

By default the value of the view parameter is waSmarty3View (adapter for Smarty 3).

To create a custom adapter, you need to define a new class (extending system class waView), save it in a file with the appropriate name (see section "Naming rules and recommendations") anywhere inside subdirectory lib/ of the application directory, and implement all necessary functionality inside it.

Implementation of a template engine adapter using the example of class waPHPView:

<?php

/**
 * Any View adapter must extend system class waView
 */
class waPHPView extends waView
{
  
    // File name extension of template files, default is .html,
    // to use pure PHP as the view, template file names must match mask *.php
    protected $postfix = '.php';
  
    // The variable to store data passed to view
    protected $vars = array();
  
    // Root template directory (is set in the constructor)
    protected $template_dir = array();
  
    // Application object waSystem
    protected $system;
  
    // Auxiliary variable to store information about the currently active template
    protected $current_template;

    public function __construct(waSystem $system, $options = array())
    {
        $this->system = $system;
    
        // Setting the root template directory,
        // by default it is the main application directory wa-apps/{APP_ID}/
        $this->template_dir = isset($options['template_dir']) ? $options['template_dir'] : $this->system->getAppPath();
    }

    /**
     * Function assign: passing data from an action/controller to the template
     */
    public function assign($name, $value = null)
    {
        if (is_array($name)) {
            $this->vars += $name;
        } else {
            $this->vars[$name] = $value;
        }
    }

    /**
     * Deleting a variable
     */
    public function clearAssign($name)
    {
        if (isset($this->vars[$name])) {
            unset($this->vars[$name]);
        }
    }

    /**
     * Clearing all data passed to the template
     */
    public function clearAllAssign()
    {
        $this->vars = array();
    }

    /**
     * Returns one or all variables passed to the template
     */
    public function getVars($name = null)
    {
        if ($name === null) {
            return $this->vars;
        } else {
            return isset($this->vars[$name]) ? $this->vars[$name] : null;
        }
    }

    /**
     * Returns the rendered HTML code of a template as a string
     */
    public function fetch($template, $cache_id = null)
    {
        ob_start();
        $this->display($template, $cache_id);
        $result = ob_get_contents();
        ob_end_clean();
        return $result;
    }

    /**
     * Renders the specified template to be displayed in the user's browser
     */
    public function display($template, $cache_id = null)
    {
        if ($this->templateExists($template)) {
            $this->current_template = $template;
            extract($this->vars);
            include($this->template_dir.'/'.$this->current_template);
        } else {
            throw new waException("Template ".$template.' not found');
        }
    }

    /**
     * Verifies whether the specified template exists
     */
    public function templateExists($template)
    {
        return file_exists($this->template_dir.'/'.$template);
    }

}