如果您曾经使用过ASP.NET MVC,那么您将熟悉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,再一次!‘会被打印出来。因此,基本上,在定义页面布局时,其所有内容都显示在页面布局的@RenderBody部分。您不需要显式地定义布局中要包含的页面。
发布于 2011-09-14 13:00:57
我不知道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>然后,可以为数据库中的每个页面定义一个top、middle和bottom模板:)
发布于 2011-09-14 13:11:16
你也可以用细枝做这件事
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 %}发布于 2012-03-04 01:22:05
我知道这是一个老问题,但是从ASP.net+MVC3开发中我找到了一个更好的解决方案。
创建一个master.php页面,如这个页面(使用doctype和其他任何东西等等)
master.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');
?>缺点是:
好处:
这绝不是一个原创的想法,我找到了另一个使用这种方法的网页,这正是我想要在我的网页中做的。
这篇文章和我在谷歌搜索如何做同样的事情时发现的一样,所以我想用我的解决方案来回答。
https://stackoverflow.com/questions/7416665
复制相似问题