0

我想知道如何在 codeigniter 中实现它,因为在控制器中总是有这个代码有点麻烦。

$this->load->view('header');
$this->load->view('content_view',$data);
$this->load->view('footer');

在 twig 中,您可以像这样定义默认模板 base.html.twig:

<html>
<body>
    {% block content %}
    {% endblock %}
</body>
</html>

然后在您的 content_view 中,您可以扩展该默认模板并添加当前控制器发送的内容:

{% extends 'base.html.twig' %}

{% block content %} 
... your data here ...
{% endblock %}

所以我只需要在我的控制器中调用它

$this->load->view('content_view',$data);

瞧,系统会加载我的默认模板以及我的 content_view 数据

我不想使用图书馆或类似的东西。我想在不使用第三方软件的情况下实现这一点。

编辑:

我在这里看到了一个好主意,第一个答案,Get the hang of CodeIgniter - Templating / loading views

但它只是接近我想要实现的,更像是树枝模板引擎

假设我想在我的默认模板、导航以及网站名称和页面标题中添加另一个块:

<html>
<head>
    <title>{{ app_name }} :: {{ page_title }}</title>
</head>
<body>
<div id="navi">
    {% block navi %}
    {% endblock %}
</div>

<div id="content">
    {% block content %}
    {% endblock %}
</div>
</body>
</html>

导航.html.twig

{% extends 'base.html.twig' %}

(% if active ? 'class="active" : '' %}

<ul>
    <li {{ active }}>Home</li>
    <li {{ active }}>About</li>
    <li {{ active }}>Contact</li>
</ul>

然后在我的控制器中,我有以下数据要传递给 content_view:

$content = array(
    'page_title' => 'About this Site', 
    'content_body' => 'blah blah, blah'
);

$data = array(
    'app_name' => 'Example',
    'page_title' => 'About',
    'active' => 'about',    // the active page to highlight in navigation
    'contents' => $content
)

$this->load->view('content_view',$data);

现在即使变量位于不同的位置,因为它们都是从一个默认页面链接的,所以这些值将一起打印。

<html>
<head>
    <title>Example :: About</title>
</head>
<body>
<div id="navi">
    <ul>
        <li>Home</li>
        <li class="active">About</li>
        <li>Contact</li>
    </ul>
</div>

<div id="content">
    <h3>About this Site</h3>

    blah, blah blah
</div>
</body>
</html>
4

1 回答 1

1

您可以遵循以下方法:

<?php
    #controller
    $data           = array();
    $data['title']  = 'Home Page';
    $data['main']   = 'index';
    $this->load->view('template', $data);   
?>

这是 template.php 文件

<!-- save as template.php -->
<html>
<head>
    <title><?=$title?></title>
</head>
<body>
<div id="navi">
    <?php $this->load->view('header') ?>
</div>

<div id="content">
    <?php $this->load->view($main) ?>
</div>
</body>
</html>

现在在 header.php 文件中执行所有与导航相关的代码。

于 2013-07-05T15:32:52.533 回答