Skip to content
This repository has been archived by the owner on Feb 27, 2023. It is now read-only.

Object references []

svallory edited this page Jul 5, 2012 · 1 revision

Square brackets follow a tag definition and contain a PHP object that is used to set the class and id of that tag. The class is set to the object’s class (transformed to use underlines rather than camel case) and the id is set to the object’s class, followed by its id. Because the id of an object is normally an obscure implementation detail, this is most useful for elements that represent instances of Models.

Object references will use the helper functions id_for() and class_for().

For example:

%div[$user]

will compile to:

<div <?php atts(array('id' => id_for($user), 'class' => class_for($user))); ?>></div>

Additionally, the second argument (if present) will be used as a prefix for both the id and class attributes. The prefix will be passed to the helpers.

%div[$user, :this_is]

will compile to:

<div <?php atts(array('id' => id_for($user, 'this_is'), 'class' => class_for($user, 'this_is'))); ?>></div>

and would be rendered as:

<div id="this_is_user_1" class="fancy this_is_user"></div>

If you require that the class be something other than the underscored object’s class, you can implement the a method called haml_object_ref or hamlObjectRef on the object returning a string. The id will come from a property called id, if it doesn't exist, the presence of a getId() method will be checked. If it's not found either, an internal counter will be used. Read more about it on the helper functions documentation.

For example, suppose you have in your User class the following code:

<?php

class User {

  ...

  public function getId() {
    return 123;
  }

  public function hamlObjectRef() {
    if(!empty($this->role))
      return $this->role;

    return 'user';
  }
}

then, the HamlPHP code

%div[$user]

will compile to

<div <?php atts(array('id' => id_for($user), 'class' => class_for($user))); ?>></div>

and can render as any of the below depending on the value of $role.

<div id="admin_123" class="admin"></div>
<div id="user_123" class="user"></div>
Clone this wiki locally