You are here

class HamlView in Sassy 7

Haml allows you to write view files in {@link Haml http://haml-lang.com/} and render them using {@link http://phamlp.googlecode.com PHamlP}.

If a .haml view is not found a .ctp or .thtml view is used. @package PHamlP @subpackage Cake

Hierarchy

Expanded class hierarchy of HamlView

File

phamlp/Cake/views/haml.php, line 35

View source
class HamlView extends View {

  /**#@+
   * Configurable Options
   */

  /**
   * @var string the extension name of the view file. Defaults to '.haml'.
   */
  var $ext;

  /**
   * @var boolean whether to use Cake's cache directory. If false the view file
   * is created in the view directory. Defaults to true.
   */
  var $useCachePath;

  /**
   * @var integer the chmod permission for temporary directories and files
   * generated during parsing. Defaults to 0755 (owner rwx, group rx and others rx).
   */
  var $filePermission;

  /**
   * @var boolean whether to cache parsed files. If false files will be parsed
   * every time.
   */
  var $cache;

  /**
   * @var array default option values.
   */
  var $defaults = array(
    'ext' => '.haml',
    'useCachePath' => true,
    'filePermission' => 0755,
    'cache' => true,
  );

  /**#@-*/

  /**
   * @var HamlParser the Haml parser
   */
  private $haml;

  /**
   * @var array Haml parser option names. These are passed to the parser if set.
   *
   * format: string DOCTYPE format
   *
   * doctype: string custom doctype. If null (default) {@link format} must be
   * a key in {@link doctypes}
   *
   * escapeHtml: boolean whether or not to escape X(HT)ML-sensitive characters
   * in script. If this is true, = behaves like &=; otherwise, it behaves like
   * !=. Note that if this is set, != should be used for yielding to
   * subtemplates and rendering partials.
   * Defaults to false.
   *
   * suppressEval: boolean Whether or not attribute hashes and scripts
   * designated by = or ~ should be evaluated. If true, the scripts are rendered
   * as empty strings.
   * Defaults to false.
   *
   * attrWrapper: string The character that should wrap element attributes.
   * Characters of this type within attributes will be escaped (e.g. by
   * replacing them with ') if the character is an apostrophe or a
   * quotation mark.
   * Defaults to " (an quotation mark).
   *
   * style: string style of output. Can be:
   * nested: output is nested according to the indent level in the source
   * expanded: block tags have their own lines as does content which is indented
   * compact: block tags and their content go on one line
   * compressed: all unneccessary whitepaces is removed. If ugly is true this
   * style is used.
   *
   * ugly: boolean if true no attempt is made to properly indent or format
   * the output. Reduces size of output file but is not very readable.
   * Defaults to true.
   *
   * preserveComments: boolean if true comments are preserved in ugly mode.
   * If not in ugly mode comments are always output.
   * Defaults to false.
   *
   * debug: integer Initial debug setting:
   * no debug, show source, show output, or show all.
   * Debug settings can be controlled in the template
   * Defaults to DEBUG_NONE.
   *
   * filterDir: string Path to filters. If specified this will be searched
   * first followed by 'vendors.phmlp.haml.filters'.
   * This allows the default filters to be overridden.
   *
   * doctypes: array supported doctypes
   * See HamlRender for default
   *
   * emptyTags: array A list of tag names that should be automatically
   * self-closed if they have no content.
   * See HamlRender for default
   *
   * inlineTags: array A list of inline tags for which whitespace is not collapsed
   * fully when in ugly mode or stripping outer whitespace.
   * See HamlRender for default
   *
   * minimizedAttributes: array attributes that are minimised.
   * See HamlRender for default
   *
   * preserve: array A list of tag names that should automatically have their
   * newlines preserved.
   */
  var $hamlOptions = array(
    'format',
    'doctype',
    'escapeHtml',
    'suppressEval',
    'attrWrapper',
    'style',
    'ugly',
    'preserveComments',
    'debug',
    'filterDir',
    'doctypes',
    'emptyTags',
    'inlineTags',
    'minimizedAttributes',
    'preserve',
    'helperFile',
  );

  /**
   * Initialises HamlView.
   * @param Controller $controller
   * @return HamlView
   */
  function __construct(&$controller) {
    parent::__construct($controller);
    foreach ($this->defaults as $key => $value) {
      $option = Configure::read("Haml.{$key}");
      $this->{$key} = is_null($option) ? $value : $option;
    }

    // foreach
  }

  /**
   * Do a sanity check on the options and setup alias to filters
   */
  private function _init() {
    $options = array();
    foreach ($this->hamlOptions as $option) {
      $_option = Configure::read("Haml.{$option}");
      if (!is_null($_option)) {
        $options[$option] = $_option;
      }
    }

    // foreach
    App::import('Vendor', 'HamlParser', array(
      'file' => 'phamlp' . DS . 'haml' . DS . 'HamlParser.php',
    ));
    $this->haml = new HamlParser($options);
  }

  /**
   * Renders a piece of PHP with provided parameters and returns HTML, XML, or
   * any other string.
   *
   * This realizes the concept of Elements, (or "partial layouts")
   * and the $params array is used to send data to be used in the
   * Element.  Elements can be cached through use of the cache key.
   *
   * Overrides View::element() to provide fallback to .ctp elements.
   *
   * @param string $name Name of template file in the/app/views/elements/ folder
   * @param array $params Array of data to be made available to the for rendered
   * view (i.e. the Element)
   * Special params:
   * cache - enable caching for this element accepts boolean or strtotime
   * compatible string.
   * Can also be an array. If an array,'time' is used to specify duration of the
   * cache.
   * 'key' can be used to create unique cache files.
   * @return string Rendered Element
   * @access public
   */
  function element($name, $params = array(), $loadHelpers = false) {
    $file = $plugin = $key = null;
    if (isset($params['plugin'])) {
      $plugin = $params['plugin'];
    }
    if (isset($this->plugin) && !$plugin) {
      $plugin = $this->plugin;
    }
    if (isset($params['cache'])) {
      $expires = '+1 day';
      if (is_array($params['cache'])) {
        $expires = $params['cache']['time'];
        $key = Inflector::slug($params['cache']['key']);
      }
      elseif ($params['cache'] !== true) {
        $expires = $params['cache'];
        $key = implode('_', array_keys($params));
      }
      if ($expires) {
        $cacheFile = 'element_' . $key . '_' . $plugin . Inflector::slug($name);
        $cache = cache('views' . DS . $cacheFile, null, $expires);
        if (is_string($cache)) {
          return $cache;
        }
      }
    }
    $paths = $this
      ->_paths($plugin);
    foreach ($paths as $path) {
      if (file_exists($path . 'elements' . DS . $name . $this->ext)) {
        $file = $path . 'elements' . DS . $name . $this->ext;
        break;
      }
      elseif (file_exists($path . 'elements' . DS . $name . '.ctp')) {
        $file = $path . 'elements' . DS . $name . '.ctp';
        break;
      }
      elseif (file_exists($path . 'elements' . DS . $name . '.thtml')) {
        $file = $path . 'elements' . DS . $name . '.thtml';
        break;
      }
    }
    if (is_file($file)) {
      $params = array_merge_recursive($params, $this->loaded);
      $element = $this
        ->_render($file, array_merge($this->viewVars, $params), $loadHelpers);
      if (isset($params['cache']) && isset($cacheFile) && isset($expires)) {
        cache('views' . DS . $cacheFile, $element, $expires);
      }
      return $element;
    }
    $file = $paths[0] . 'elements' . DS . $name . $this->ext;
    if (Configure::read() > 0) {
      return "Not Found: " . $file;
    }
  }

  /**
   * Renders and returns output for given view filename with its
   * array of data.
   *
   * @param string Filename of the view
   * @param array Data to include in rendered view
   * @return string Rendered output
   * @access protected
   */
  function _render($___viewFn, $___dataForView, $loadHelpers = true, $cached = false) {
    if (substr($___viewFn, strrpos($___viewFn, '.')) == $this->ext) {
      $cachedViewFile = $this
        ->_getCachedViewFileName($___viewFn);
      if (!$this->cache || @filemtime($___viewFn) > @filemtime($cachedViewFile)) {
        if (empty($this->haml)) {
          $this
            ->_init();
        }
        file_put_contents($cachedViewFile, $data = $this->haml
          ->parse($___viewFn));
        @chmod($cachedViewFile, $this->filePermission);
      }
      return parent::_render($cachedViewFile, $___dataForView, $loadHelpers, $cached);
    }
    else {
      return parent::_render($___viewFn, $___dataForView, $loadHelpers, $cached);
    }
  }

  /**
   * Generates the cached view file path.
   * @param string source view file path
   * @return string cached view file path
   * @access private
   */
  private function _getCachedViewFileName($file) {
    $cachedViewFile = str_replace(substr($file, strrpos($file, '.')), '.ctp', $file);
    if ($this->useCachePath) {
      $cachedViewFile = str_replace(VIEWS, CACHE . 'haml' . DS, $cachedViewFile);
      if (!is_file($cachedViewFile)) {
        @mkdir(dirname($cachedViewFile), $this->filePermission, true);
      }
    }
    return $cachedViewFile;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
HamlView::$cache property * * every time.
HamlView::$defaults property *
HamlView::$ext property *
HamlView::$filePermission property * * generated during parsing. Defaults to 0755 (owner rwx, group rx and others rx).
HamlView::$haml private property *
HamlView::$hamlOptions property * * * format: string DOCTYPE format * * doctype: string custom doctype. If null (default) {@link format} must be * a key in {@link doctypes} * * escapeHtml: boolean whether or not to escape X(HT)ML-sensitive characters * in script.…
HamlView::$useCachePath property * * is created in the view directory. Defaults to true.
HamlView::element function * Renders a piece of PHP with provided parameters and returns HTML, XML, or * any other string. * * This realizes the concept of Elements, (or "partial layouts") * and the $params array is used to send data to be used in the *…
HamlView::_getCachedViewFileName private function * Generates the cached view file path. *
HamlView::_init private function * Do a sanity check on the options and setup alias to filters
HamlView::_render function * Renders and returns output for given view filename with its * array of data. * *
HamlView::__construct function * Initialises HamlView. * Overrides view::__construct
view::$api_version public property The views-api version this view was created by.
view::$args public property
view::$argument public property Stores the argument handlers which are initialized on this view.
view::$attachment_after public property
view::$attachment_before public property
view::$base_database public property Allow to override the used database which is used for this query.
view::$base_field public property
view::$base_table public property
view::$build_info public property
view::$built public property State variable.
view::$core public property The core version the view was created for.
view::$current_display public property Identifier of the current display.
view::$current_page public property
view::$db_table public property Overrides views_db_object::$db_table
view::$description public property The description of the view, which is used only in the interface.
view::$disabled public property Is the view disabled.
view::$display public property Stores all display handlers of this view.
view::$display_handler public property The current used display plugin.
view::$editing public property State variable.
view::$empty public property The area handlers for the empty text which are initialized on this view.
view::$executed public property State variable.
view::$exposed_data public property
view::$exposed_input public property
view::$exposed_raw_input public property
view::$field public property Stores the field handlers which are initialized on this view.
view::$filter public property Stores the filter handlers which are initialized on this view.
view::$footer public property Stores the area handlers for the footer which are initialized on this view.
view::$header public property Stores the area handlers for the header which are initialized on this view.
view::$human_name public property The human readable name of the view.
view::$is_attachment public property
view::$items_per_page public property
view::$name public property The name of the view.
view::$offset public property
view::$old_view public property
view::$override_path public property Allow to override the path used for generated urls.
view::$override_url public property Allow to override the url of the current view.
view::$parent_views public property
view::$query public property Where the $query object will reside:.
view::$relationship public property Stores the relationship handlers which are initialized on this view.
view::$result public property Where the results of a query will go.
view::$row_index public property Stores the current active row while rendering.
view::$sort public property Stores the sort handlers which are initialized on this view.
view::$style_options Deprecated public property Stored the changed options of the style plugin.
view::$style_plugin public property The current used style plugin.
view::$tag public property The "tags" of a view. The tags are stored as a single string, though it is used as multiple tags for example in the views overview.
view::$total_rows public property
view::$use_ajax public property
view::$vid public property The id of the view, which is used only for views in the database.
view::access public function Determine if the given user has access to the view.
view::attach_displays public function Run attachment displays for the view.
view::build public function Build the query for the view.
view::build_title public function Force the view to build a title.
view::choose_display public function Get the first display that is accessible to the user.
view::clone_view public function Safely clone a view.
view::copy public function Make a copy of this view with IDs, handlers sanitized
view::db_objects static function Returns the complete list of dependent objects in a view, for the purpose of initialization and loading/saving to/from the database.
view::delete public function Delete the view from the database.
view::delete_locale_strings public function Delete localized strings.
view::destroy public function Unset references so that a $view object may be properly garbage collected.
view::display_objects public function Returns a list of the sub-object types used by this view. These types are stored on the display, and are used in the build process.
view::end_query_capture public function Add the list of queries run during render to buildinfo.
view::execute public function Execute the view's query.
view::execute_display public function Execute the given display, with the given arguments. To be called externally by whatever mechanism invokes the view, such as a page callback, hook_block, etc.
view::execute_hook_block_list public function Called to get hook_block information from the view and the named display handler.
view::execute_hook_menu public function Called to get hook_menu() info from the view and the named display handler.
view::export public function Export a view as PHP code.
view::export_locale_strings public function Export localized strings.
view::fix_missing_relationships public function Attempt to discover if the view has handlers missing relationships.
view::get_base_tables public function Create a list of base tables eligible for this view. Used primarily for the UI. Display must be already initialized.
view::get_breadcrumb public function Get the breadcrumb used for this view.
view::get_current_page public function Get the current page from the pager.
view::get_exposed_input public function Figure out what the exposed input for this view is.
view::get_human_name public function Return the human readable name for a view.
view::get_items_per_page public function Get the items per page from the pager.
view::get_offset public function Get the pager offset from the pager.
view::get_path public function Get the base path used for this view.
view::get_title public function Get the view's current title.
view::get_url public function Get the URL for the current view.
view::init_display public function Set the display for this view and initialize the display handler.
view::init_handlers public function Acquire and attach all of the handlers.
view::init_localization public function Find and initialize the localization plugin.
view::init_pager public function Initialize the pager.
view::init_query public function Do some common building initialization.
view::init_style public function Find and initialize the style plugin.
view::is_cacheable public function Is this view cacheable?.
view::is_translatable public function Determine whether a view supports admin string translation.
view::load_views static function Static factory method to load a list of views based upon a $where clause.
view::post_execute public function Unset the current view, mostly.
view::preview public function Preview the given display, with the given arguments.
view::pre_execute public function Run attachments and let the display do what it needs to do prior to running.
view::process_locale_strings public function Process strings for localization, deletion or export to code.
view::render public function Render this view for a certain display.
view::render_field public function Render a specific field via the field ID and the row #.
view::save public function Save the view to the database.
view::save_locale_strings public function Send strings for localization.
view::set_arguments public function Set the arguments that come to this view. Usually from the URL but possibly from elsewhere.
view::set_current_page public function Change/Set the current page for the pager.
view::set_display public function Set the display as current.
view::set_exposed_input public function Set the exposed filters input to an array. If unset they will be taken from $_GET when the time comes.
view::set_items_per_page public function Set the items per page on the pager.
view::set_offset public function Set the offset on the pager.
view::set_title public function Override the view's current title.
view::set_use_ajax public function Whether or not AJAX should be used. If AJAX is used, paging, tablesorting and exposed filters will be fetched via an AJAX call rather than a page refresh.
view::start_query_capture public function Set up query capturing.
view::update public function Perform automatic updates when loading or importing a view.
view::use_pager public function Determine if the pager actually uses a pager.
view::validate public function Make sure the view is completely valid.
view::_build public function Internal method to build an individual set of handlers.
view::_build_arguments public function Build all the arguments.
view::_init_handler public function Attach all of the handlers for each type.
view::_post_execute public function Run the post_execute() on all active handlers.
view::_pre_query public function Run the pre_query() on all active handlers.
view::_save_rows public function Save a row to the database for the given key.
views_db_object::add_display public function Add a new display handler to the view, automatically creating an id.
views_db_object::add_item public function Add an item with a handler to the view.
views_db_object::export_row public function Export a loaded row.
views_db_object::generate_display_id public function Generate a display id of a certain plugin type.
views_db_object::generate_item_id public static function Generates a unique ID for an item.
views_db_object::get_item public function Get the config of an item (field/sort/filter/etc) on a given display.
views_db_object::get_items public function Get an array of items for the current display.
views_db_object::init public function Initialize this object, setting values from schema defaults.
views_db_object::load_row public function Load the object with a row from the database.
views_db_object::new_display public function Create a new display and a display handler for it.
views_db_object::save_row public function Write the row to the database.
views_db_object::set_item public function Set the config of an item (field/sort/filter/etc) on a given display.
views_db_object::set_item_option public function Set an option on an item.