如何使用PHP将HTML转换为实时可编辑模板?

时间:2012-01-25 15:10:39

标签: php html css templates system

如何将HTML模板转换为实时的php可编辑模板?我希望能够设置标题,描述,添加图像和链接。 (比如behance上传系统)

有人可以将我链接到教程吗? 非常感谢!

2 个答案:

答案 0 :(得分:2)

要以简单的方式执行此操作,您应该执行以下3个步骤: 1-在HTML模板中添加自定义标签 2-创建一个类以使HTML模板可写 3-加载课程,编写模板,显示页面

  1. 首先,在HTML模板(template.html)中插入一些自定义标记,如下所示:

  2. 然后,创建一个快速类(class.php)以使您的自定义标记可写:

        class Template { var $contents;
    
    
        function load($file) {
            if ($fp = fopen($file, "r")) {
                $this->contents = fread($fp, filesize($file));
                fclose($fp);
            }
        }
    
        function replace($str,$var) {
            $this->contents = str_replace("<".$str.">",$var,$this->contents);
        }
    
        function show() {
            $search = array(
                    '/\t/', //Remove Tabs
                    '/<!--[^\[-]+?-->/', //Remove Comments
                    '/\n\n/' //Remove empty lines
                    );
                $replace = array(
                    '',
                    '',
                    ''
                    );
            $this->contents = preg_replace($search, $replace, $this->contents);
            echo $this->contents;
        }
    }
    
  3. 完成此操作后,您必须创建一个在标签内写入的功能。在我的示例中,为了能够编写<page_title>标记,请将以下代码添加到class.php文件中:

    function writetitle($s) {
        $GLOBALS['writes']++;
        $GLOBALS['page_title'] .= $s;
        return;
    }
    
    1. 最后,您需要做的就是创建page.php。加载课程,写下您想要的内容,然后显示结果。
    2. 类似的东西:

      <?php
          require_once('class.php');    //Load Class
          $template = new Template;    
          $template->load("template.html"); //Load HTML template
      
          //Some query :
          $query = mysql_query('SELECT...');
          $res = mysql_num_rows($query);
      
          writetitle('my page title went live!, '.$res.'');  //write your content
      
      
          $template->show(); //Generate the page
      ?>
      

      writetitle 现在充当 echo ,因此您可以进行查询以及所需的一切。

      最后你有3个文件: tempalte.html:您的模板 class.php:你的模板引擎 page.php:使用模板的示例页面。

      希望它有所帮助。 ;)

答案 1 :(得分:0)

  1. 将.html文件另存为.php
  2. 在你的PHP中,加载你想要填充模板的数据(这是一个很大的主题,也是学习PHP的基础;不是我可以在SO上为你解答的)
  3. 将已加载的变量回显到模板中。初学者的方法就是这样。在“example.php”中:

  4. <?php
    //1. Populate the value from PHP somehow, such as from the GET variables in your HTTP request
    $personsNameFromPHP = $_GET['personsNameFromGETVariables'];
    
    //2. Echo the variable out in your markup like this:
    ?>
    <div class="personsName">
    <?php echo $personsNameFromPHP; ?>
    </div>
    

    W3Schools是一个不错的起点。如果您已经了解PHP语法,请先了解MySQL数据库的工作原理以及PHP如何访问它们。如果你不懂PHP,那么W3Schools也有一些链接。

    http://www.w3schools.com/PHP/php_mysql_intro.asp

    HTH。