我最近写了我的第一个WP插件,该插件添加了一个短码,用于将自定义的jQuery图像库嵌入到帖子中。它主要仅将大部分HTML倒入帖子中,以及初始化所需的JavaScript。

但是,我必须按照PHP的字符串进行程序性构建HTML输出。这种标签的汤总是让我发疯,我习惯于使用MVC框架,这些框架提供了辅助功能和生成HTML的部分模板之类的东西。

有帮助吗?

解决方案

@byran M.我倾向于使用两种构造,我经常看到其他WordPress开发人员经常使用,这让我感到惊讶,但我非常喜欢它们。

1.)Heredocs

您可以将大量文本存储为 埃尔多克斯 可能看起来像这样的字符串,所以我可以存储担心混合单引号和双引号:

   $html=<<<HTML
<input type="{$type}" size="{$size}" id="{$id}" class="{$class}" value="{$value}" />
HTML;

请注意,变量可以作为数组传递给函数,然后 extract() the_content()get_the_content() WordPress并不总是使这种编码风格变得容易。)

phpstorm

2.)使用数组的字符串串联

我想使用的另一个成语是将内容收集到数组中,然后 implode()

function my_get_form_and_fields($input_items) {
    $html = array();
    $html[] = '<form name="my_form" method="get">';
    foreach($input_items as $input_item) {
        extract($input_item);
        $html=<<<HTML
<input type="{$type}" size="{$size}" id="{$id}" class="{$class}" value="{$value}" />
HTML;
    $html[] = '</form>';
    return implode("\n",$html);         
}   

其他提示

检查此功能的PHP:

http://php.net/manual/en/function.ob-start.php

您可以缓冲随附的文件,该文件仅包含其中的HTML代码,将其放入PHP变量中。这将使维护更加干净。

因此,您最终得到了这样的事情:

ob_start();
   include('path/to/my/html/file.php');
   $includedhtml = ob_get_contents();
ob_end_clean();

    // From within a method in our controller
    $this->data['message'] = 'Pass this on to the template please';
    $this->render('my-template');

    // Meanwhile, in the /plugin/views/my-template.php file
    <h2>The Separation of Logic and Views</h2>
    <p><?php echo $this->data['message'];?></p>

这取决于HTML和JS的类型。

JavaScript

html

echo $firstblock;
echo $shortcodecontent;
echo $lastblock;

与其尝试以程序性的方式构建它,不如构建一个包含您所有不同HTML块的对象(是的,PHP支持对象),而是指示它使用哪些块以及要退回的数据。这将节省大量时间。

许可以下: CC-BY-SA归因
scroll top