We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Volt-like block with pure PHP

I have a simple question: is there any way to create a Volt-like block in a view with pure PHP? I'm not using the Volt template engine, but I would like to use this functionality to create a block for holding JavaScript references at the bottom of my layout view.



98.9k
edited Oct '14

Using just PHP, you can create a function and then call it wherever you want to include the block:

$my_block = function()
{
    echo $this->tag-> stylesheetLink("style.css");
};
$my_block();


5.6k
edited Dec '14

I wasn't very clear about what I was trying to do. Basically I'm trying to replicate the ASP.NET MVC functionality where I can define a section at the bottom of my layout like this:

@Html.RenderSection( "scripts" );

Then I can add a script in my view like this, and it will be included at the bottom of the page instead of linked as a separate file:

@section scripts {
    <script>
        console.log('foobar');
    </script>
}

I've managed to get similar functionality in Phalcon by including this at the bottom of my layout:

foreach ($scripts as $script) {
    echo $script;
}

Then in my view I can add a script like this:

$scripts[] = "
    <script>
        console.log('foobar');
    </script>
";

I believe I can achieve this with Volt blocks, but is there a better way without Volt?