【问题标题】:How to get php variable before included file如何在包含文件之前获取php变量
【发布时间】:2014-10-02 02:52:58
【问题描述】:

我有一个模板,它使用 php 包含文件 $content 来显示页面的主要内容。我希望根据内容更改页面标题。我可以在包含的 $content php 文件中声明 $pagetitle,但问题是在布局中,内容是在 pagetitle 之后加载的。

我不想每次加载页面时都从我的代码中设置 $pagetitle,我宁愿将它放在相关的内容文件中,这样每次我包含页面时它都会自动设置。我该怎么做?

    <div class="container">
        <main class="content">
           <div id="ctopspace"><h2><?php echo $pagetitle;></h2></div>
             <div id="cleftspace"></div>             
             <?php  include $content;?>
        </main><!-- .content -->
    </div><!-- .container-->

【问题讨论】:

  • 将整个 .content 类移动到 $content 包含?
  • 您可以使用 $_GET 找出您当前的位置。这是假设您正在使用某种路由系统。

标签: php html


【解决方案1】:

您可以在所有其他代码之上包含您的文件和echo 相应的内容和标题变量,然后完成

$content = file_get_contents( your_content_file );

在您包含的文件中。

<?php include $contentFile ?>

//...later in the code

<h2><?= $pagetitle; ?></h2>
<div id="cleftspace"></div>             
<?=  $content; ?>

注意:&lt;?= 是&lt;?php echo 的开放式短标签。它可能在您的服务器上被禁用。

【讨论】:

  • 谢谢 我不确定我是否完全理解。我的代码中的 $content 是指其中包含 html 的 php 文件。如果我在代码上方包含它,它将在错误的位置输出 html。
  • 没有。 (感谢您的评论。)您应该只将整个 php 文件保存在一个变量中并在需要的地方输出它。
【解决方案2】:

之前

file_put_contents('page-title.txt', $pagetitle);

在 $content 文件中

<h2><?php echo @file_get_contents('page-title.txt'); ?></h2>

ps:@只是跳过file_exists这一步)

【讨论】:

    猜你喜欢
    • 2011-04-12
    • 1970-01-01
    • 2016-08-06
    • 1970-01-01
    • 2012-01-12
    • 2021-08-15
    • 2014-01-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多