【问题标题】:Quitting Smarty to do it manually退出 Smarty 手动完成
【发布时间】:2016-01-04 02:00:53
【问题描述】:

我面临的问题是我不确定如何在没有框架或模板引擎的情况下进行开发。我以这种方式开始编码,现在我想学习基础知识。

我曾经使用这个 MVC 架构,使用 Codeigniter 和 Smarty 作为模板引擎。我现在要做的是使用原始 php 而不提到这两种工具。

我不知道如何“复制”Smarty的“块”和“扩展”的概念。

我以前定义了一个 base.tpl 文件,它有 html 头,只有 body 标记,以及基本的 css 和 js 文件(总是在网站的每个页面中使用的文件),如下所示:(sn- p)

 <!DOCTYPE html>
 <head>
 <meta charset="utf-8" />
 <title>Dashboard</title>
 <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" name="viewport" />
 <meta content="" name="description" />
 <meta content="" name="author" />

 <!-- ================== BEGIN BASE CSS STYLE ================== -->
 <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
 <link href="{site_url()}assets/css/animate.min.css" rel="stylesheet" />
 <!-- ================== END BASE CSS STYLE ================== -->

 <!-- ================== BEGIN PAGE LEVEL CSS STYLE ================== -->
 {block name='custom_css'}{/block}
 <!-- ================== END PAGE LEVEL CSS STYLE ================== -->

 <!-- ================== BEGIN BASE JS ================== -->
 <script src="{site_url()}assets/plugins/pace/pace.min.js"></script>
 <!-- ================== END BASE JS ================== -->
</head>
<body>
  <div id="page-container" class="fade page-sidebar-fixed page-header-fixed">
    <div id="header" class="header navbar navbar-default navbar-fixed-top">
        <div class="container-fluid">
            {include file='base/header.tpl'}
        </div>
    </div>
    <!-- BEGIN PAGE -->
    <div class="page-content">
        <!-- BEGIN PAGE CONTAINER-->
        <div class="container-fluid">
            <!-- BEGIN PAGE HEADER-->
            <div class="row-fluid">
                <div class="span12">                        
                    <!-- BEGIN PAGE TITLE & BREADCRUMB-->
                    {include file='admin/base/breadcrumb.tpl'}
                    <!-- END PAGE TITLE & BREADCRUMB-->
                </div>
            </div>
            <!-- END PAGE HEADER-->
            {block name='content'}{/block}
        </div>
        <!-- END PAGE CONTAINER-->    
    </div>
    <!-- END PAGE -->

然后当我需要调用这个 base.tpl 时,我这样做了:

{extends file='base/base.tpl'}

{block name='custom_css}
   <link href="{site_url()}assets/css/pages/blog.css" rel="stylesheet" type="text/css"/>
 {/block}

{block name='content'}
   <div class="row">
      <div class="col-md-3 col-sm-6">
        <div class="widget widget-stats bg-green">
        <div class="stats-icon stats-icon-lg"><i class="fa fa-globe fa-fw"></i></div>
        <div class="stats-title">TODAY'S VISITS</div>
        <div class="stats-number">7,842,900</div>
        <div class="stats-progress progress">
            <div class="progress-bar" style="width: 70.1%;"></div>
        </div>
        <div class="stats-desc">Better than last week (70.1%)</div>
      </div>
   </div>

我一直在搜索,但我担心我找不到正确的搜索词,因为我找不到答案。

我希望得到指导!

【问题讨论】:

  • 这只是一些 if this echo that 包裹
  • 对不起,我没有关注你
  • 以上所有内容(取第一个块)是根据name='custom_css' 标准确定在页面上回显的内容,因此它不超过if($name=='custom_css'){echo 'some css here';}
  • @Limon 如何对您得到的所有答案提供一些反馈。已经一个月了。你尝试了什么?

标签: php html include smarty extends


【解决方案1】:

另一种方法可能是做这样的事情。我觉得这可能更接近于模板引擎的最终结果,但使用的是 {block} 语法。

index.php

<?php
$blocks = array();
function add_block($name, $callback){
    global $blocks;
    ob_start();
    $callback();
    $output = ob_get_flush();
    $blocks[$name] = $output;
}

function get_block($name){
    global $blocks;
    if(!empty($blocks[$name])){
        return $blocks[$name];
    }
    return '';
}

//stop any errors from being output. 
ob_start();

//include the page code
include 'page.php';
$cleanup = ob_end_clean();

//now output the template
include 'template.php';

page.php

<?php

add_block('head', function(){
    ?><script type="text/javascript">/* Some JS */</script><?php
});

add_block('body', function(){
    ?><p>Some body text goes here</p><?php
});

template.php

<html>
    <head>
        <title>Site Title</title>
        <?php echo get_block('head'); ?>
    </head>
    <body>
        <?php echo get_block('body'); ?>
    </body>
    <?php echo get_block('after_body'); ?>
</html>

【讨论】:

    【解决方案2】:

    我不确定它有多聪明,实际上我自己从未使用过模板引擎。但也许这就是它的完成方式。

    假设我们有:

    index.php
    page.php
    template.php
    

    当我们转到 index.php 时,它可以启动并输出缓冲区并包含 page.php。在包含后捕获输出缓冲区并使用一些正则表达式来匹配在其中找到的块并将它们放入变量中。

    现在对 template.php 执行相同的操作,并找到其中的所有块,并将这些块替换为 page.php 中的块。

    我实际上并不认为模板引擎是这样做的。但这是一种可能的方式。

    【讨论】:

      【解决方案3】:

      一个非常小的自制模板引擎 基于使用数组钩子的正则表达式替换 “手动”解析模板

      (但我承认,smarty 更实用) 有任何问题都可以在这里回复我

      正则表达式匹配整个文件的术语,如 {term-_}, 并将其替换为将在渲染时执行的 php 条件。

      如果在 $vars 中没有找到一个标记",它将被一个空字符串简单地替换

      引擎

      function parse($vars, $tpl)
      {
          return preg_replace
          (
              '#\{([a-z0-9\-_]*?)\}#Ssie',
              '( ( isset($vars[\'\1\']) )
                  ? $vars[\'\1\']
                  : \'\'
              );',
              file_get_contents(TEMPLATE_DIR.$tpl)
          );
      }
      

      部分索引

           <html>
                <head>...</head>
                {body}
           </html>
      

      身体的一部分

          <body>
               <div class='ui'>{username}</div>
          </body>
      

      用法

          <?php
          // include engine function
          define("TEMPLATE_DIR", __DIR__."templates/");
          require_once("library/parse.php");
      
          // just init $vars on top of index
          $vars = [];
      
          // and access and fill it anywhere
          $vars = ["username" => $_SESSION["user"]];
      
          // prepare the body including previous $vars declarations
          $vars["body"] = parse($vars, 'body');
      
          echo parse($vars, 'index');
      

      输出

          <html>
               <head>...</head>
               <body>
                   <div class='ui'>Stack Overflow :)</div>
               </body>
          </html>
      

      您可以通过使用常量和防止双重换行标记 {{}} 或更多,或放置调试跟踪来改进它...

      将此添加到引擎的启动以防止包含对象括号的模板可能被错误地解释为模板标记:

      $out = file_get_contents(TEMPLATE_DIR.$tpl);
      $out = str_replace("{{}}", "{}", $out);
      

      要使用常量,您可以使用 perform as like :

          $empty = (DEBUG) ? "_EMPTY_" : "";
          return preg_replace
          (
              '#\{([a-z0-9\-_]*?)\}#Ssie', 
              '( ( isset($vars[\'\1\']) ) 
                  ? $vars[\'\1\'] 
                  : ( defined(\'_\'.strtoupper(\'\1\').\'_\') 
                      ? constant(\'_\'.strtoupper(\'\1\').\'_\') 
                      : $empty 
                  ) 
              );',
              $out
          );
      

      注意:

      __DIR__ 
      

      在我的代码中使用对 PHP 有效 >= 5.3.0 试试 但你可以使用

      dirname(__FILE__)
      

      对于 PHP

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-10-16
        • 2015-05-28
        相关资源
        最近更新 更多