Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RenderBody in php

Tags:

php

asp.net

If you have used ASP.NET MVC you'd be familiar with RenderBody. Basically, you have one layout page and several body pages. Something like this:

layout.cshtml:

<html>
  <head>
    <title>Your Title</title>
  </head>
  <body>
    @RenderBody()
  </body>
</html>

index.cshtml:

@{
   layout = "layout.cshtml";
}

<p>Hello World!</p>

So when you call index.cshtml, all of its content will be shown in the layout's @RenderBody section. This is really useful when your pages use a single layout.

Now, my question is, how could I achieve something similar to the code above in php?

EDIT

For those who are not familiar with ASP.NET, when you have an index2.cshtml file like this:

@{
   layout = "layout.cshtml";
}

<p>Hello World, once again!</p>

Then when you call index2.cshtml this time 'Hello World, once again!' would be printed. So basically, when you define the page's layout, all of its content is displayed in the @RenderBody section of its layout. You don't have to explicitly define what page to include in the layout.

like image 341
Shaokan Avatar asked Dec 31 '25 11:12

Shaokan


2 Answers

I don't know ASP.NET but here's how you'd most probably do the same in PHP:

<html>
  <head>
    <title>Your Title</title>
  </head>
  <body>
    <?php include('body.php'); ?>
  </body>
</html>

and body.php could then contain

<p>Hello World!</p>

(very) Simple routing example:

$router    =  new RequestRouter; //this class would route a request to a set of templates stored in a persistent storage engine like a database
$request   =  $_SERVER['QUERY_STRING'];
$templates =  $router->resolve($request); //would return an array with the templates to be used
include('master.php');

master.php:

<html>
  <head>
    <title>Your Title</title>
  </head>
  <body>
    <div>
        <?php include($templates['top']); ?>
    </div>
    <div>
        <?php include($templates['middle']); ?>
    </div>
    <div>
        <?php include($templates['bottom']); ?>
    </div>
  </body>
</html>

You could then define a top, middle and bottom template for each page in your database :)

like image 86
thwd Avatar answered Jan 03 '26 00:01

thwd


You can do it (also) with Twig:

main_layot.twig:

<!DOCTYPE html>
<html>
    <head>
        <title>Example</title>
    </head>
    <body>
            {% block content %}{% endblock %}
    </body>
</html>

and content:

{% extends "main_layout.twig" %}

{% block content %} Content {% endblock %}

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!