Greg Gum
Greg Gum

Reputation: 38109

PHP Mixing html and code

(Preamble: Am new to PHP, coming from a C# background where I am used to very clean code. Am currently working on my own Wordpress site which has a purchased theme.)

I have seen this type of code in a WordPress theme:

<a href="<?php echo esc_url( home_url( '/' ) ); ?>"><img src="<?php echo esc_url( $logo ); ?>" alt="<?php echo esc_attr( get_bloginfo( 'name' ) ); ?>" id="logo"/></a>

I find this very hard to read compared to the refactored:

<?php
            echo '<a href="';
            echo esc_url( home_url( '/' ) ); 
            echo "><img src=";
            echo esc_url( $logo ); 
            echo " alt=";
            echo esc_attr( get_bloginfo( 'name' ) ); 
            echo '" id="logo"/></a>'
?>

But this is the easiest by far:

<?php
        get_anchor($url, $imgsource, $alt, $id);
?>

get_anchor being a custom function that echos an anchor configured according to the parameters.

But surely I am not the first to think of this. Are there any existing libs that have a set of functions that return properly formatted html like in this example? Is there something I am missing?

Upvotes: 0

Views: 333

Answers (3)

Joren
Joren

Reputation: 3315

I've written a function that returns a HTML tag based on the pure PHP output:

function tag($name, $attrs, $content) {
    $res = '';
    $res .= '<' . $name;
    foreach($attrs as $key => $val)
        $res .= ' ' . $key . '="' . $val . '"';

    $res .= isset($content) ? '>' . $content . '</'.$name.'>' : ' />';

    return $res;
}
  • $name is the tagname (e.g. a)
  • $attrs is a key, value array with attributes (e.g. array('href','http://google.com/'))
  • $content is the content / body of the tag (an other element or text)

Example basic use:

echo tag('a', array('href' => 'http://google.com/'),'Google');

Example nested use with multiple children:

echo tag('ul',array(),
        tag('li',array(),'one') . 
        tag('li',array(),'two') . 
        tag('li',array(),'three')
    );

Upvotes: 1

Sumit Kumar
Sumit Kumar

Reputation: 1902

Most of the PHP frameworks provide such libraries to out put html through parameterized functions, most of them are part of view layer if the framework follows MVC pattern.

but if you are not using any of the framework then you may use these libraries from here

PHP Pear Packages

And for building forms in particular see

HTML_QuickForm2

Upvotes: 0

MSI
MSI

Reputation: 884

I believe what you are looking for are templates like Smarty. They are the cleanest way to display information as code and view are completely separated.

However Wordpress do not use them, I don't know why actually, probably because most PHP programmers are not used to it.

Upvotes: 0

Related Questions