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

时间:2013-10-11 10:51:29

标签: cakephp cakephp-2.0 block

有人可以向我解释如何在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>

所以将其分解为两个元素(heading1和heading 2)

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

3 个答案:

答案 0 :(得分:7)

你应该创建一个如下的元素。

// 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');
?>

答案 1 :(得分: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.

在您的布局中,您可以将视图块代码提取/显示为

echo $this->fetch('block_name'); // anywhere in the layout.

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

答案 2 :(得分:0)

在你的布局或元素中:     

    $this->fetch ("block_name");
    
无论你何时定义你的块或你覆盖它...每次在你的其他元素你可以做$ this-&gt; start(“block_name”)或$ this-&gt; append(“block_name”)... cakephp会将所有操作“合并”到该块并将它们放在适当的位置(在布局中定义)...

使用块的一个示例...想象一下你的版块标题中的一个css块和你的页脚中的javascript块...就像那个特定的css或javascript特定的fonctionnality它们将被添加到那个块并且你不会在生成的HTML中间有脚本和CSS ...

我希望能帮到你