在PHP中创建设计模板文件

时间:2011-08-25 12:56:57

标签: php css

我打算创建一个模板PHP文件,这个模板只服务于设计,而不是内容。目的是减少开发时间,因为在创建新的PHP文件或新模块时,我只需要专注于PHP文件的主要功能而不是设计。一旦我使用模板创建了新文件,它应该能够显示一致的设计并提供其特定的功能。

问题在于我不确定如何使模板的设计工作并应用于创建的所有新文件,无论位置如何(只要它在根目录中)。

举个例子:

root directory (www.example.com): /
homepage (www.example.com/index.php): /index.php
css file: /style/style.css
template file: /template.php
newly created file (www.example.com/subone/find/css/file.php): /subone/find/css/file.php
another newly created file (www.example.com/subtwo/locate/css.php): /subtwo/locate/css.php

主页的内容(基于template.php创建,但CSS文件位置是硬编码的):

<html>
<head>
<title>Testing</title>
<link rel="stylesheet" type="text/css" href="style/style.css" />
</head>
<body>
<div id="header">logo and login form goes here
<div class="nav"> navigation goes here;</div>
</div>
<div id="main">main content goes here;</div>
<div id="footer">footer goes here; </div>
</body>
</html>

但是,当我创建一个新文件/subone/find/css/file.php时 必须手动更改和指定css的位置,如下所示:

<html>
<head>
<title>Testing</title>
<link rel="stylesheet" type="text/css" href="../../../style/style.css" />
</head>
<body>
<div id="header">logo and login form goes here
<div class="nav"> navigation goes here</div>
</div>
<div id="main">main content goes here;</div>
<div id="footer">footer goes here;</div>
</body>
</html>

所以,我想要实现的是,在创建一个新文件(/subone/find/css/file.php)时,我不需要做任何事情,我可以直接专注于主要部分:

<html>
<head>
<title>Testing</title>
...style.css is handled automatically
</head>
<body>
<div id="header">logo and login form goes here
<div class="nav"> navigation goes here</div>
</div>
<div id="main">main content goes here;
<?php
//I can continue to edit the file from this line onward
echo "I am concentrating on the main function of file.php right now!!";
?>
</div>
<div id="footer">footer goes here;</div>
</body>
</html>

示例页面可以看到(只有所需的设计):neoborn.kodingen.com
我接受任何答案,只要它能达到我的意图(模板)。

谢谢:)

4 个答案:

答案 0 :(得分:2)

为什么在引用模板文件中的CSS文件和其他资源时不使用绝对路径?

例如:

<link rel="stylesheet" type="text/css" href="/style/style.css" />

答案 1 :(得分:0)

有两个选项,

  1. 为css文件使用绝对路径<link rel=stylesheet href="/style/style.css">
  2. 使用HTML的<base>元素可以使页面上的所有相对路径与之相关。

答案 2 :(得分:0)

<强>的index.php

<?php define('BASE_URL', 'http://localhost'); ?>

<强>的template.php

<link rel="stylsheet" type="text/css" href="<?php echo BASE_URL; ?>/style/style.css ?>" />

答案 3 :(得分:0)

我会使用易于安装的模板引擎。这将有助于加快开发速度,并且仍然可以让您自由地做任何您喜欢的PHP。

尝试http://www.raintpl.com/,您应该快速轻松地安装并重新编写页面编码。如果将它包含在PHP inc文件夹中,它将对您创建的每个PHP文件都可用。因此,您不需要在每个PHP文件的顶部添加包含行。