2011-09-14 31 views
1

如果您使用過ASP.NET MVC,那麼您會熟悉RenderBody。基本上,你有一個佈局頁面和幾個正文頁面。事情是這樣的:php中的RenderBody

layout.cshtml:

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

index.cshtml:

@{ 
    layout = "layout.cshtml"; 
} 

<p>Hello World!</p> 

所以,當你調用index.cshtml,它的所有內容都將在佈局的@RenderBody部分被所示。當您的頁面使用單個佈局時,這非常有用。

現在,我的問題是,我怎麼能實現類似於上面的代碼在PHP中?

編輯

對於那些誰不熟悉ASP.NET,當你有一個index2.cshtml文件是這樣的:

@{ 
    layout = "layout.cshtml"; 
} 

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

然後當你調用index2.cshtml這次「 Hello World,再一次!將被打印。所以基本上,當您定義頁面的佈局時,其所有內容都會顯示在其佈局的@RenderBody部分。您不必明確定義要在佈局中包含的頁面。

+0

你是指不使用模板? –

+0

對不起,我的意思是框架:) – Shaokan

回答

2

我不知道ASP.NET但這裏是你如何會最有可能做同樣的PHP:

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

body.php然後可能含有

<p>Hello World!</p> 

(很)簡單路由示例:

$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> 

你可以在你的數據庫:)

+0

也許我必須更具體。當您調用具有相同佈局的第二頁時,其內容將顯示。我的意思是,如果你有index2.cshtml,它的內容是'Hello World',那麼它就會顯示出來。所以,也許最接近你的建議,將使用開關在不同情況下包含不同的文件。 – Shaokan

+0

或者創建一個路由引擎並將URL路由到一組正文模板以包含:) – thwd

+0

你能舉個例子說明如何做到這一點嗎? – Shaokan

2

你可以做到這一點(也)與Twig然後爲每個頁面定義一個topmiddlebottom模板:

main_layot .twig:

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

和內容:

{% extends "main_layout.twig" %} 

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

我知道這是一個老問題,但來自ASP.net + MVC3開發,我發現了一個更好的解決方案。

創建master.php頁,像這樣(與DOCTYPE和任何其他等,你的想法)

高手。PHP:

<head> 
    my_stuff, meta tags, etc. 
    <title><?php echo $page_title; ?></title> 
</head> 
<body> 
    <?php include('$page_content') ?> 
</body> 

下一個我有一個單獨的文件夾只是爲了保持整潔,你並不需要(如內容/) 將所有內容文件此文件夾中,你在你的ASP.net包括頁面,我會打電話給我的如default.php

如default.php:

<div> 
    Hello World 
</div> 

然後創建一個你想打加載頁面內容的文件,我會打電話給我的index.php文件

的index.php:

<?php 
    $page_title = 'Hello Example'; 
    $page_content = 'Content/default.php'; 
    include('master.php'); 
?> 

的缺點:每每一頁

  • 兩個文件,這可以通過直接把頁面內容的變量被規避,但我更喜歡整潔一個單獨的文件。

優點:

  • 沒有多餘的.htaccess或任何其他服務器要求
  • 允許的變量無限數量由每個頁面
  • 模仿了ASP.net RenderBody()函數傳遞完全像你想要的:D

這絕不是一個原創的想法,我發現另一個網頁,利用這種方法,它是前實際上我想在我的網頁上做的事情。

這個SO帖子和我在google搜索如何做同樣的事情時發現的一樣,所以我想用我的解決方案來回答。

相關問題