0

(前言:我是 PHP 新手,来自 C# 背景,我习惯了非常干净的代码。目前正在我自己的 Wordpress 网站上工作,该网站有一个购买的主题。)

我在 WordPress 主题中看到过这种类型的代码:

<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>

与重构相比,我发现这很难阅读:

<?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>'
?>

但这是迄今为止最简单的:

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

get_anchor 是一个自定义函数,它回显根据参数配置的锚点。

但我肯定不是第一个想到这一点的人。是否有任何现有的库具有一组返回正确格式的 html 的函数,如本例中?有什么我想念的吗?

4

3 回答 3

1

我编写了一个基于纯 PHP 输出返回 HTML 标记的函数:

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

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

    return $res;
}
  • $name是标记名(例如a
  • $attrs是具有属性的键、值数组(例如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')
    );
于 2013-10-20T18:20:53.827 回答
0

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.

于 2013-10-20T18:27:35.627 回答
0

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

于 2013-10-20T19:01:38.047 回答