March 10, 2010

03/10, @9:57am:

This tutorial will teach you how to use content_for().

As an example, let’s use this default layout:

<body>
  <div id="header">
    <h1>Our big bold header</h1>
  </div>
  <div id="content">
    <div id="side">
      <?php if (isset($side)) echo $side; ?>
    </div>
    <div id="main">
      <?= $content; ?>
    </div>
  </div>
  </body>

See that we have not only our usual $content variable to render the content, but also a second variable called $side, which will be responsible to render our sidebar.

Next, create a controller function to handle the home action of our app:

# GET /
dispatch('/', 'home');
function home() {
  return render('home.html.php');
}

And, the home.html.php view file:

<!-- begining 'side' block -->
<?php content_for('side'); ?>
<ul>
  <li>Item 1</li>
  <li>Item 2</li>
</ul>
<?php end_content_for(); ?>
<!-- ending 'side' block -->

<h2>Home Action</h2>
<p>Main content…</p>

Finally, refresh the page to see that our sidebar now receives the content of our 'side' block.

To improve our code, let’s use the partial function, which will render view file at that point within the current rendered view.

Change the file home.html.php to:

<!-- begining 'side' block -->
<?php content_for('side'); ?>
  <?= partial('_sidebar.html.php'); ?>
<?php end_content_for(); ?>
<!-- ending 'side' block -->

<h2>Home Action</h2>
<p>Main content…</p>

And create a file called _sidebar.html.php in the view folder. Note that the underscore is optional.

<ul>
  <li>Item 1</li>
  <li>Item 2</li>
</ul>

Now you can break your views into modular files. It’s useful to insert specific CSS or JS and to make some AJAX stuff.

blog comments powered by Disqus