Get a contextual array for your node-links

Last modified: August 27, 2009 - 00:34

Often if you are annoyed by the fact that links under the nodes are only availble as plain text strings, for example when you only want the "read more" link, or only the "comments" links. (example of usage)

This PHPtemplate-specific snipped creates an additional variable: an array with much nicer link data.

function _phptemplate_variables($hook, $vars) {
  switch ($hook) {
    case 'node':
      foreach ($vars[node]->links as $link) {
        preg_match("/<a\s*.*?href\s*=\s*['\"]([^\"'>]*).*?>(.*?)<\/a>/i",$link, $matches);
        $vars["nodelinks"][] = array('url'=>$matches[1], 'text' => $matches[2]);
    }
      print_r($vars);
    break;
  }
  return $vars;
}

Note: The code above creates an array containing the 2 keys.

Other Solution to this task

In http://drupal.org/node/21538#comment-81773 is another solution that gets a contextual array for nodelinks, which does not require the _phptemplate_variables function.

By using an ungreedy modifier to the regexp, the expression can be much simpler.
See: http://drupal.org/node/43888#comment-81797 describes a similar approach for comment links.

Note: some links change text (eg x comments) and can't be used in the associative array.

 
 

Drupal is a registered trademark of Dries Buytaert.