sppc42
sppc42

Reputation: 3302

In PHP, call/inject something in base php file from the included php file

Am new to PHP, so I might be totally off in my understanding, but am trying to see how to work the below out:

template.php:

<html>
    <head>
        <title>Some title</title>
        // Add a PHP 'Placeholder' here to inject some HTML if $filename = BodyInstance.php
    </head>
    <body>
        <?php include($filename); // $filename = BodyInstance.php or can be any other php file  ?> 
    </body>
</html>

BodyInstance.php

<p>
    This is a dummy body text
    <?php // Inject something into the placeholder of template.php ?>
</p>

So, I have a template.php file, which loads different views into the body depending upon the $filename parameter. Now, one of the views, BodyInstance.php needs to have some extra tags present in the head element. This needs to happen on the server side, I don't want to do it via jQuery on the client side on document.ready.

Any hints?

Thanks

Upvotes: 0

Views: 74

Answers (2)

sppc42
sppc42

Reputation: 3302

I ended up using the file based loading pattern for loading the tags based on the presence of a $filename-tags.php file

<html>
    <head>
        <title>Some title</title>
        // Add a PHP 'Placeholder' here to inject some HTML if $filename = BodyInstance.php
        <?php if (file_exists($filename ."-tags") include ($filename) ?>
    </head>
    <body>
        <?php include($filename); // $filename = BodyInstance.php or can be any other php file  ?> 
    </body>
</html>

Upvotes: 0

Justinas
Justinas

Reputation: 43507

I think there is few options. But usually it's made using ob_* functions:

[index.php]

ob_start(); // start Output Buffer
require "content.php"; // Will create $headerContent and returns some html.
$content = ob_get_contents(); // Get content from buffer
ob_end_clean(); // Clear buffer

require "baseHtml.php";

[content.php]

<?php $headerContent = '<style>body {background-color: red;}</style>'; ?>
<p>Some text here</p>

[baseHtml.php]

<html>
  <head>
     <?php echo $headerContent; ?>
  </head>
  <body>
     <?php echo $content; ?>
  </body>
</html>

Final output will be:

<html>
  <head>
     <style>body {background-color: red;}</style>
  </head>
  <body>
     <p>Some text here</p>
  </body>
</html>

This technique is usually used in CMS'es, because it allows to send headers after some content was "outputted" (only to buffer) and allows to preprocess content.

Upvotes: 1

Related Questions