用PHP编写Head部分

时间:2014-09-24 17:09:13

标签: php html include

我将几个站点从HTML转换为PHP以获取动态元素,并且已经能够使用页眉和页脚(使用php include())。但是,我对如何做头部感到困惑。这就是我用简单的HTML:

<head>
  <!--[if lt IE 9]>
  <script src="http://html5shim.googlecode.com/svn/trunk/html5.js">
  </script>
  <![endif]-->
  <meta charset="UTF-8" />
  <meta name="description" content="Liberty Resource Directory. The ultimate curated directory to find what you need."/>
  <meta name="keywords" content="ethan glover, lrd, liberty resource directory"/>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <link href="stylesheets/lrdstylesheet.css" rel="stylesheet" media="screen">
  <title>Liberty Resource Directory</title>
</head>

我可以轻松添加HTML5Shim脚本,元字符集,视口(是的,我将删除最大比例)和样式表链接。

问题在于:

如何以可以传递单个页面描述,关键字和标题的方式编写.php文件? (这样我就可以将上面的代码放在一个php文件中,并将其包含在每一页上。)

或者我只需要排除描述,关键字和标题,每次都重写这些部分吗?

以下是答案:(由Alejandro Arbiza提供)

head.php

<head>
  <!--[if lt IE 9]>
  <script src="http://html5shim.googlecode.com/svn/trunk/html5.js">
  </script>
  <![endif]-->
  <meta charset="UTF-8" />
  <meta name="description" content="<?php echo $description;?>"/>
  <meta name="keywords" content="<?php echo $keywords;?>"/>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="../stylesheets/lrdstylesheet.css" rel="stylesheet" media="screen">
  <title><?php echo $title;?></title>
</head>

index.html(包括上面的代码)

<?php
    $description="Liberty Resource Directory. The ultimate curated directory to find what you need.";
    $keywords="ethan glover, lrd, liberty resource directory";
    $title="Liberty Resource Directory";
    include 'scripts/head.php';
?>

最终结果:

http://libertyresourcedirectory.com/

1 个答案:

答案 0 :(得分:1)

您可以使用变量作为描述和关键字(或者您想要的任何其他内容)。然后,当构建页面的时候,您只需使用相应的值设置变量。

<head>
    <!--[if lt IE 9]>
    <script src="http://html5shim.googlecode.com/svn/trunk/html5.js">
    </script>
    <![endif]-->
    <meta charset="UTF-8" />
    <meta name="description" content="<?php echo $description; ?>"/>
    <meta name="keywords" content="<?php echo $keywords; ?>"/>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link href="stylesheets/lrdstylesheet.css" rel="stylesheet" media="screen">
    <title>Liberty Resource Directory</title>
</head>

所以,假设你有page1.php和page2.php:

<?php
// page1.php
$description = "This is page one";
$keywords = "page one";
include 'header.php';
?>

<!-- Page content --> 

<?php include 'footer.php'; ?>

<?php
// page2.php
$description = "This is page two";
$keywords = "page two";
include 'header.php';
?>

<!-- Page content --> 

<?php include 'footer.php'; ?>

当然,我假设整个HTML标头位于header.php文件中,包括<html><head><body>