Skip to content

Instantly share code, notes, and snippets.

@hugodias
Last active January 19, 2022 06:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save hugodias/a9f2868fbe5582b49bb80af7c44d909e to your computer and use it in GitHub Desktop.
Save hugodias/a9f2868fbe5582b49bb80af7c44d909e to your computer and use it in GitHub Desktop.
content_tag function in PHP to work as Rails content_tag function
<?php
/**
* @param $tag
*
* @return string
*/
function close_tag($tag)
{
return "</" . $tag . ">";
}
/**
* @param array $attr
*
* @return null|string
*/
function generate_attr_string($attr = array())
{
$attr_string = null;
if ( ! empty($attr)) {
foreach ($attr as $key => $value) {
// If we have attributes, loop through the key/value pairs passed in
//and return result HTML as a string
// Don't put a space after the last value
if ($value == end($attr)) {
$attr_string .= $key . "=" . '"' . $value . '"';
} else {
$attr_string .= $key . "=" . '"' . $value . '" ';
}
}
}
return $attr_string;
}
/**
* @param $tag
* @param array $attr
*
* @return string
*/
function open_tag($tag, $attr = array())
{
$attr_string = generate_attr_string($attr);
return "<" . $tag . " " . $attr_string . ">";
}
/**
* Create a dynamic html tag
*
* @see http://andrewberls.com/blog/post/formatting-dynamic-html-tags-in-php
*
* @param string $tagName
* @param string $content
* @param array $attr
*
* @example content_tag("h1", "Hello", array("class" => "title"));
*
* @return string
*/
function content_tag($tagName = "h2", $content = "", $attr = array())
{
return open_tag($tagName, $attr) . $content . close_tag($tagName);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment