dongnanke4106 2018-04-26 20:22
浏览 52
已采纳

使用php函数显示html [关闭]

I am Working on a little project and I want to apply some sort of templating to display content in between a master template file when included on each page without using any templating engine. Currently i have the following pages.

layout.template.php

<!DOCTYPE html>
<html lang="en">
<head>

</head>
<body>
  <!-- page content displays here -->
  <?php show_content(); ?>
</body>
</html>

index.php

<?php function show_content(){ ?>
<div>
    <h1>Home page</h1>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>
</div>
<?php } 
include 'layout.template.php';
?>

second.php

<?php function show_content(){ ?>
<div>
    <h1>Second page</h1>
    <p>some other content</p>
</div>
<?php }
include 'layout.template.php';
?>

i use the show_content() function to define the html that would be rendered into the layout.template.php file on each page. When layout.template.php is include it makes a call to the function and displays the html code in it based on the page it is included it. my question is

Is this a good idea or practice? What alternative do i have to achieving this (other than using templating engines)?

  • 写回答

1条回答 默认 最新

  • drblhw5731 2018-04-26 20:45
    关注

    There is not a perfect answer, because there are too many ways how to do it.

    A good solution would be to separate the view (HTML) from the logic (PHP). Probably MVC would be a good answer.

    If you want to practice only:

    Create a folder and put all your HTML files into that folder. Then you have your PHP file which includes a function (or maybe even a method) that calls that HTML content which you would like to display. If your HTML content also includes PHP, it would be better not to name it myFile.php. In this case call it myFile.phtml, so that it is clear to your, it is HTML but part of it is PHP as well.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 @microsoft/fetch-event-source 流式响应问题
  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False