蛋糕PhP块 - 如何使用它们?

Rob*_*ons 10 cakephp block cakephp-2.0

任何人都可以向我解释如何在CakePhP 2.0中使用"视图块"吗?

我已经阅读了关于cakephp网站的文档,但是对于新手用户来说它遗漏了很多...例如我需要哪些文件,如何在代码中调用块,代码块是否需要自己的文件夹/控制器/型号/视图等?我真的输了!

如果有人可以从头到尾解释如何使用块作为侧边栏,这将是伟大的.

例如,我有一个侧边栏,我想在不同的页面上使用,但我想打破侧栏到不同的元素,以在块内调用,例如

<div class="heading1">
  <h2>Heading 1</h2>
</div>
<div class="ul-list1">
<ul> 
<li>list item 1</li>
<li>list item 2</li>
</ul>
</div>
<div class="heading2">
  <h2>Heading 2</h2>
</div>
<div class="ul-list1">
<ul> 
<li>list item 3</li>
<li>list item 4</li>
</ul>
</div>
Run Code Online (Sandbox Code Playgroud)

所以把它分成两个元素(heading1和heading 2)

我将如何编写块的代码,我在哪里插入此代码以及我需要哪些页面?(请将此目标瞄准新手CakePhP用户,因为我对此非常困惑!)

Vik*_*hak 6

你应该创建一个像下面这样的元素.

// app/views/elements/headings.ctp
<?php $this->start('heading1'); ?>
<div class="heading1">
    <h2>Heading 1</h2>
</div>
<div class="ul-list1">
    <ul> 
        <li>list item 1</li>
        <li>list item 2</li>
    </ul>
</div>
<?php $this->end(); ?>


<?php $this->start('heading2'); ?>
<div class="heading2">
    <h2>Heading 2</h2>
</div>

<div class="ul-list1">
    <ul> 
        <li>list item 3</li>
        <li>list item 4</li>
    </ul>
</div>
<?php $this->end(); ?>
// end element file

// include the element first before getting block in the views or layout file.
<?php 
    echo $this->element('headings');
?>

// after that you will able to display block anywhere inside view files or layout also with following statements.

<?php
    // for heading first 
    echo $this->fetch('heading1');

    // for heading second.
    echo $this->fetch('heading2');
?>
Run Code Online (Sandbox Code Playgroud)


Vik*_*hak 1

您可以在视图或元素中使用以下代码。

// for start the block code
$this->start('block_name');

// your html code will goes here, even you can also specify the element reference.

$this->end(); // close the block.
Run Code Online (Sandbox Code Playgroud)

在您的布局中,您可以获取/显示视图块代码,如下所示

echo $this->fetch('block_name'); // anywhere in the layout.
Run Code Online (Sandbox Code Playgroud)

确保您在视图和布局中指定了相同的块名称。