Skip to content

Instantly share code, notes, and snippets.

@berkes
Created October 26, 2010 09:42
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save berkes/646608 to your computer and use it in GitHub Desktop.
Save berkes/646608 to your computer and use it in GitHub Desktop.
Drupal template helpers to render values.
<?php
/**
* Renders a value cleaned. Simply pulls value through check_plain.
*
* Example usage:
* @code
* r('foo'); //=> "Foo"
* r('<script alert(infected)>Foo'); //=> "Foo"
* r("<em>123</em>"); //=> 123
* @endcode
*
* @param $value Mixed
* The value to be printed. Value must be of a printable type.
* @return
* Nothing. Function prints value directly.
*/
function r($value) {
print check_plain($value);
}
/**
* Renders a value raw.
*
* Example usage:
* @code
* r_raw('foo'); //=> "Foo"
* r_raw('<script alert(infected)>Foo'); //=> "<script alert(infected)>Foo"
* r_raw("<em>123</em>"); //=> "<em>123</em>"
* @endcode
*
* @param $value Mixed
* The value to be printed. Value must be of a printable type.
* @return
* Nothing. Function prints value directly.
*/
function r_raw($value) {
print $value;
}
/**
* Renders a field, joined
*
* Example usage:
* @code
* r_join(', ', $field_hometown); //=> "Nijmegen, <em>GLD</em>"
* r_join(', ', $field_hometown, 'safe'); //=> "Nijmegen, GLD"
* r_join(', ', $field_hometown, 'value'); //=> "Nijmegen<script alert(SECURITY BREACH)>, <em>GLD</em>"
* @endcode
*
* @param $glue String
* Used to join the values. Will be passed along to implode().
* @param $field Array
* A field, as presented to the (node) templates. Consists of a list of values
* separated into value_types. E.g.
* ["field_hometown"]=>
* array(1) {
* [0]=>
* array(3) {
* ["value"]=>
* string(10) "Heerenveen"
* ["safe"]=>
* string(10) "Heerenveen"
* ["view"]=>
* string(10) "Heerenveen"
* }
* }
* @param $value_type String, optional defaults to 'view'
* The value_type to be used. Normally one of "view", "safe" or "value".
* See example usage for how these /might/ be filed. In general they won't differ
* too much. Never use "value" unless you are very sure about the safety of the value.
* @return
* Nothing. Function prints value directly.
*/
function r_join($glue, $field, $value_type = 'view') {
foreach($field as $field_value) {
$values[] = $field_value[$value_type];
}
print join($glue, $values);
}
?>
@berkes
Copy link
Author

berkes commented Oct 27, 2010

As discussed on http://identi.ca/conversation/57034397#notice-57540830: r_join could, or should have $glue otional and therefore second argument. But that would be inconsistent with join() and implode(). Which, being "PHPish" are wrong too, but at least consistently wrong.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment