Skip to content Skip to sidebar Skip to footer

Php Adding Stylesheets To Header

Is there a way to add stylesheets to the header after including the header file? Say we have this code: class content { public $stylesheets = array(); public function addS

Solution 1:

The final html code is always generated at the end. Here is an example how to proceed with pure php/html. Your index.php could look something like this:

<?php// ...// Define the stylesheets to use$content = new content();
$content->addStylesheets(array('home.css', 'slider.css'));

// ...// Print template at the end
ob_start();
include'your_html_template.php';
print ob_get_clean();

The your_html_template.php is your template file as shown in the question.


You can define variables before executing the template to have a more clear separation of php code and html. Then the index.php could look like this:

<?php// ...// Define the stylesheets to use$content = new content();
$content->addStylesheets(array('home.css', 'slider.css'));
$htmlStyleHeaderTags = $content->getStylesheets();  // Define variable with html header tags// ...// Print template at the end
ob_start();
include'your_html_template.php';
print ob_get_clean();

And then you can use the variable $htmlStyleHeaderTags in your template:

<html><head><title>Title</title><linkrel="stylesheet"type="text/css"href="default.css" /><?phpprint$htmlStyleHeaderTags; ?></head><bod...

Solution 2:

As @szapio already sad, it makes more sense to build the HTML at the very end.

Anyway, a "dirty" solution would be to hack your DOM with jQuery by putting the following before the </body>-tag (having jQuery included in the <head>):

<script>
$(document).ready(function() {
    $('head').append('<link rel="stylesheet" href="test.css" />');
});
</script>

You really shouldn't consider doing this, because the CSS file will be loaded after everything else, meaning you will see the unstyled elements as long as the CSS file is not loaded yet…

Post a Comment for "Php Adding Stylesheets To Header"