Page "template" layout. HTML </head> header.php vs page.php - php

I've asked a similar question before, but I've got a more specific question about this "style" of creating a page.
I have 3 pages for a template, header.php, page.php and footer.php. I'm trying to allow myself to easily edit parts of the site within a single page, but also be able to have extra things in on per-page basis. My current structure is:
header.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Website Name<? if ($title) echo ' – ' . $title; ?></title>
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="stylesheet" type="text/css" href="reset.css">
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
page.php
<?
$title = 'Page Title';
require_once('includes/header.php');
?>
<!-- Any extra stuff for the header goes here -->
</head>
<body>
Page content goes here.
<? require_once('includes/footer.php'); ?>
footer.php
<footer>
I am a footer
</footer>
</body>
</html>
Although this works, I cannot make a publicly editable header (menus etc) that easily since my header.php page does not contain anything in the <body>. However, closing the <head> in header.php would not allow me to add extra files (such a page-specific javascript) on per-page basis. To my knowledge, CSS and javascript being included within the <body> tag is not a good idea.
I'm guessing a further file (say, menu.php) would be required and included at the top of each page, after the <head> tag? However, that doesn't seem that easy to read/natural, I feel there must be a better solution?

One easy solution is to have inside "header.php" a line to echo the content of $extraHeaders:
<!DOCTYPE html>
<html>
<head>
<?php echo $extraHeaders ?>
...
Then, any page you want to add specific headers to (stylesheet, javascript file, etc.), you just include it in the $extraHeaders variable:
$extraHeaders = '<script type="text/javascript" src="myscripts.js"></script>'
And it will be automatically be included in the headers for that page.
To solve the problem of syntax highlighting and avoiding to have to escape the quotation marks, you can use the output buffer syntax:
ob_start();
?>
<your html goes here> Alternatively, you can include an html file here.
<?php
$extraHeaders = ob_get_contents();
ob_end_clean();
...
This will allow you to use a variable, as previously suggested, but with syntax highlighting, and there is no need to escape anything.

Make an _autoload() script to pre-load all those php files.
This way when ever there is anything new to put, you can always go tho the script containing the _autoload() function and update it there.
Btw, putting javascript at the very end of the <body> tag is actually a good practice.

You can use ob_start + regex ( tags like {title} or {scripts} to have an access at the end of loading the "page".

Related

wordpress get_header() on a page template getting the head content inside of the body tag

I am having trouble with my Wordpress template page. When calling get_header() in the template page, the content of the head is appearing inside the body tag and causing trouble. I couldn't find a solution for this.
This is what I mean :
page inspect element
page template :
<?php
/*
* Template Name: sub services
*/
get_header();
?>
<h1>sub page</h1>
<?php
get_footer();
?>
header.php :
<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
<meta charset="<?php bloginfo('charset'); ?>">
<?php wp_title();?>
<link rel="icon" type="image/png" href="/favicon.png">
<link href="https://fonts.googleapis.com/css2?family=Lemonada:wght#600&display=swap" rel="stylesheet">
<script src="https://kit.fontawesome.com/90928eb6b7.js" crossorigin="anonymous"></script>
<?php wp_head(); ?>
</head>
<body id="theme-body" <?php body_class(); ?>>
<header>
<h1>Main Header</h1>
</header>
and I have added a page in wordpress admin and linked it to the template.
wordpress add page
Everything works fine except that the content of the head is in the body tag. when calling get_header(). In the template.php I have checked my error log and its fine. I dont know what is causing this problem or what I'm doing something wrong.
Your header.php file contains the full body (including the closing </body>) and even the closing </html> tag. Your page template then appends to that some more HTML and a footer - that's invalid HTML and can't really be intended, is it?
Browser will probably try to fix those errors by adding missing or omitting superfluous tags, but in this case none of that will come up with the intended result - it will rather lead to a result like the one you are seeing.
The header.php file can contain the opening <body> tag, but not the closing </body>. But it should contain the Wordpress loop, and inside that the_content() to load the actual page content, and also the other WP functions to fetch heading, featured image etc.
After that, you usually fetch the footer using get_footer();, which might contain the closing </body> tag, if that's not in the page template.
So, the biggest problem in your code are the closing </body> and </html> tags and the resulting invalid HTML.

Inline Javascript with Fat-Free Layouts

I'm working with PHP Fat Free and I am attempting to create a layout/sublayout system which will eventually mimic MVC to some extent. I have a main layout which has placeholders (essentially the backend sets different sublayout or partial file paths and then the view takes care of calling the rendering of that file name. This all works great.
The issue I'm running into is when I need inline javascript in my sublayout to run after scripts in the main layout (after the jquery include line, for instance). In a previous framework I was using, I was able to do us output buffering ob_start and ob_get_clean to grab the script in the sublayout and then pass that to the layout to display below the script line. I hope that makes sense, but if not, here's the current code I'm working with in F3.
The route:
$f3->route('GET /test',
function($f3) {
// set the sublayout name
$f3->set('sublayout', 'testpage.php');
// render the whole shebang
echo View::instance()->render('testlayout.php');
}
);
The layout:
<!DOCTYPE html>
<html>
<head>
<title>Test Layout</title>
</head>
<body>
<h1>Test Layout</h1>
<?php echo View::instance()->render($sublayout) ?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js" />
<!-- inline script should go here -->
</body>
</html>
The sublayout:
<h2>My Test Page</h2>
<div id='message'></div>
<script>
// This code needs to be placed AFTER the jquery include in the main layout
$(function(){
$('#message').html('This is my message');
});
</script>
I tried extending the view to include a "beginRegion" and endRegion function that basically handled the ob_start and ob_get_clean portion so that my inline script could be picked up, but once I'm in the sublayout I wasn't able to figure out how to pass that buffered code back to the layout so it could be echo'd after the jquery include.
Before you tell me that I should not be using inline script, I know this and most things I do are in external script files which I have a solution for including, but there are times when I need it inline and that's where I'm stuck.
Is there a way to handle what I'm trying to do with output buffering, or better yet is there a better way to solve this than the output buffering approach?
Update:
Best practices generally dictate that you should include the script at the bottom of the page right before the closing body tag. If I put the script above the sublayout, it breaks both our FE best practices and has the disadvantage of blocking the rest of the page while the script downloads. That's why I'd like to keep it structured the way I have noted instead of placing the jquery include ABOVE the sublayout.
I don't understand what's the problem.
Your layout is:
<!DOCTYPE html>
<html>
<head>
<title>Test Layout</title>
</head>
<body>
<h1>Test Layout</h1>
<?php echo View::instance()->render($sublayout) ?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js" />
<!-- inline script should go here -->
</body>
</html>
You want to include sublayout after jquery usage. So why not to write it like this? :
<!DOCTYPE html>
<html>
<head>
<title>Test Layout</title>
</head>
<body>
<h1>Test Layout</h1>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js" />
<!-- inline script should go here -->
<?php echo View::instance()->render($sublayout) ?>
</body>
</html>
Also You can write custom function. Lets say You've folder with partials or something else more structured and want to use it:
$f3->set('partial',
function($file) {
$file .= (strpos($file, '.php')>0)? '' : '.php';
if(!is_file($file)) return '';
return View::instance()->render($file);
}
);
and then use it like:
<!DOCTYPE html>
<html>
<head>
<title>Test Layout</title>
</head>
<body>
<h1>Test Layout</h1>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js" />
<!-- inline script should go here -->
{{ #partial('partials/testpage') }}
</body>
</html>
I knew why You want to do so. But what's the problem to decouple scripts in scripts.php file and HTML,php part to another file and render them as needed? (:
From a google groups discussion I had, someone offered up a JS solution that might work:
inside your layout:
<head>
<script>
var callbacks=[];
</script>
</head>
<body>
<script src="...jquery.min.js"/>
<script>
$.each(callbacks,function(i,func){func.call(null,jQuery);}) //<< triggers all queued callbacks
</script>
</body>
inside your sublayout:
<h2>My Test Page</h2>
<div id="message"></div>
<script>
callbacks.push(function($){
//do something with jQuery
});
</script>
Here's the link:
https://groups.google.com/forum/#!topic/f3-framework/iGcDuDueN8c

Alternative to CSS in body tag?

In my login system in my site I wanted the user's selected CSS to be loaded after validation was complete. The only problem is that my PHP is located in the body element and I ECHOed the user's CSS link there. I know this is "bad", but what else can I do?
if (isset($_SESSION['loggedin'])){
ECHO $_SESSION['style'];
}
else
{
ECHO 'green';
}
ECHO ".css' />";
The PHP script echos some text in the body after the user is logged in, this is why I cannot put the PHP script in the header.
I'm under the assumption that you're not at all familiar with the basics of PHP, so I'll break it down as simply as I can. If your document is able to execute PHP (which it sounds like it can because you have things happening in the body), all you need to do is wrap the PHP code with <?php and ?> for it to parse as PHP.
You shouldn't put stylesheets inside your body. Indeed, that is something that no one will recommend. What you can do, however, is execute PHP in the head of your document.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>title</title>
<link rel="stylesheet" href="style.css">
<?php
echo "<link rel='stylesheet' href='{$_SESSION['user_css']}'>";
?>
<script src="script.js"></script>
</head>
<body>
<?php
echo 'body text';
?>
</body>
</html>
It doesn't matter where you decide to inject PHP code into your document, it will render as you wish. I'd suggest an MVC solution, but if this is just a small, one-off file, feel free to inject PHP wherever you want it, as often as you need it.
http://php.net/manual/en/language.basic-syntax.phptags.php
You can load the user css after the document is loaded using jQuery.
<script>
$(document).ready(function() {
$(head).append('<style>
<?php echo($user_css); ?>
</style>');
});
</script>
Though just adding a section to output the CSS in the head would be easier to maintain in the future and doesn't need the page to load. A dramatic enough change on a slow(ish) connection and the user will see the flicker as the CSS loads their style.
you could use some jQuery to append the style in the <head>:
$(head).append('<style><?php echo user_css ?></style>');

Handling page-specific JavaScript in PHP header files

When designing a website in PHP, you typically have a header.php file that you include in every page on the site. The header.php file would include the <head> tag (among other things). However, I often find that I need to put page-specific JavaScript within the <head> tag.
The way I've handled this in the past is by adding IF statements to my header to determine what pieces of JavaScript should be outputted (i.e. IF this is the home page, output the JavaScript needed for the home page, IF this is the about page, output the JavaScript needed for the about page, etc.).
This is probably a terrible way to do it. What is the standard practice?
Well, first of all, <script> tags do not need to be located in the header. It's perfectly valid to put them anywhere in the HTML document.
But if you're determined to include them in the header, a simple solution is to declare a variable that the header should echo which contains your script tags. For example:
<?php
$scripts = "<script src='script.js' type='text/javascript'></script>";
include("header.php");
?>
And then your header.php script would like as follows:
<html>
<head>
<!-- header stuff goes here -->
<?php /*echo out scripts */ echo $scripts; ?>
</head>
<body>
<!-- part of body goes here -->
Assuming you are actually including header.php in every file, just define an array before you include header.php and add the extra scripts to that. Then in header.php, have it check for that array and write out extra script tags if necessary:
mypage.php:
$extra_scripts = array('jquery.js','jquery-ui.js');
include('header.php');
// Rest of your code.
header.php:
if (is_array($extra_scripts)) {
foreach( $extra_scripts as $script ) {
// Render a script tag
}
}
If you use a templating engine like Twig, you can inherit a base template as opposed to including a header and a footer and modify the 'blocks' defined in that base.
For example purposes, your base template might include a content block and a header_javascript block like so
{% block header_javascript %}
<script src='/js/jquery.js' type='text/javascript'></script>
{% endblock %}
Then, in your child template, you can override this block, call {{ parent() }} and then add your additional, page-specific scripts.
I can see that your question has been answered very clearly. but I would like to add something.
Well, technically, it is valid to place you script tag anywhere in your document but it is better to place your script at the end of document, unless necessary. it will let visitor still see your html and javascript yet to be download, and BTW normally you don't need to run you script until DOM is ready.
This is how I do it:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Page Title</title>
<meta name="description" content="Page Description" />
<!-- Includes header stuff, css, js, google analytics, etc.. -->
<? include('header.php'); ?>
</head>
<body>
...
This allow me to avoid repetitive coding while adding flexibility to my pages.

How to import/include a CSS file using PHP code and not HTML code?

I have googled a lot but it seems that I am doing something wrong.
I want to do this:
<?php
include 'header.php';
include'CSS/main.css';
...
?>
However, my page prints the CSS code.
Note: I want to use PHP to include the CSS file, and not use
I also do you want to rename my CSS file to a PHP file as some website mentioned.
Any clues?
Many thanks.
You have to surround the CSS with a <style> tag:
<?php include 'header.php'; ?>
<style>
<?php include 'CSS/main.css'; ?>
</style>
...
PHP include works fine with .css ending too. In this way you can even use PHP in your CSS file. That can be really helpful to organize e.g. colors as variables.
You are including the CSS code as text in your PHP page. Why not just link it in the traditional fashion?
<link rel="stylesheet" href="CSS/main.css" type="text/css">
you can use:
<?php
$css = file_get_contents('CSS/main.css');
echo $css;
?>
and assuming that css file doesn't have it already, wrap the above in:
<style type="text/css">
...
</style>
To use "include" to include CSS, you have to tell PHP you're using CSS code. Add this to your header of your CSS file and make it main.php (or styles.css, or whatever):
header("Content-type: text/css; charset: UTF-8");
This might help with some user's connections, but it theoretically (read: I haven't tested it) adds processor overhead to your server and according to Steve Souder, because your computer can download multiple files at once, using include could be slower. If you have your CSS split into a dozen files, maybe it would be faster?
Steve's blog post: http://www.stevesouders.com/blog/2009/04/09/dont-use-import/
Source: http://css-tricks.com/css-variables-with-php/
<?php
define('CSSPATH', 'template/css/'); //define css path
$cssItem = 'style.css'; //css item to display
?>
<html>
<head>
<title>Including css</title>
<link rel="stylesheet" href="<?php echo (CSSPATH . "$cssItem"); ?>" type="text/css">
</head>
<body>
...
...
</body>
</html>
YOUR CSS ITEM IS INCLUDED
This is an older post, however as the info is still relevant today an additional option may help others.
Define a constant for the file path per Stefan's answer. The
definition can be placed at the top of the PHP page itself, or within
an included/required external file such as config.php.
(http://php.net/manual/en/function.include.php)
Echo the constant in PHP tags, then add the filename directly after.
That's it!
Works for other linked files such as JavaScript as well.
<?php
define('CSS_PATH', 'template/css/'); //define CSS path
define('JS_PATH', 'template/js/'); //define JavaScript path
?>
<!-- Doctype should be declared, even in PHP file -->
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="<?php echo CSS_PATH; ?>main.css">
<script type="text/javascript" src="<?php echo JS_PATH; ?>main.js"></script>
</head>
<body>
</body>
</html>
If you want to import a CSS file like that, just give the file itself a .php extension and import it anyway. It will work just fine :)
You can also do the following:
Create a php file in includes folder, name it bootstrap_css.php for example
paste the css code files to file created above
<?php
$minCss=' <link href="bootstrap/css/bootstrap.min.css" rel="stylesheet">';
$business = '<link href="bootstrap/css/modern-business.css" rel="stylesheet">';
echo $minCss;
echo $business;
?>
in the html header, include the css files as follows
<?php include_once 'includes/bootstrap_css.php'; ?>
You could do this
<?php include("Includes/styles.inc"); ?>
And then in this include file, have a link to the your css file(s).
I don't know why you would need this but to do this, you could edit your css file:-
<style type="text/css">
body{
...;
...;
}
</style>
You have just added here and saved it as main.php. You can continue with main.css but it is better as .php since it does not remain a css file after you do that edit
Then edit your HTML file like this. NOTE: Make the include statement inside the tag
<html>
<head>
<title>Sample</title>
<?php inculde('css/main.css');>
</head>
<body>
...
...
</body>
</html>
I solved a similar problem by enveloping all css instructions in a php echo and then saving it as a php file (ofcourse starting and ending the file with the php tags), and then included the php file.
This was a necessity as a redirect followed (header ("somefilename.php")) and no html code is allowed before a redirect.
Just put
echo "<link rel='stylesheet' type='text/css' href='CSS/main.css'>";
inside the php code, then your style is incuded. Worked for me, I tried.
This is the format of what I have which works:
<head>
<title>Site Title</title>
<?php include 'header.php'; ?>
</head>
Inside my header.php I have:
<!doctype html>
<html class="no-js" lang="en">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="shortcut icon" type="image/png" href="assets/images/icon/favicon.ico">
<link rel="stylesheet" href="assets/css/bootstrap.min.css">
The file name must be something other than a .CSS index. Write the following:
<link rel="stylesheet" href="style.css" type="text/css" />
The best way to do it is:
Step 1:
Rename your main.css to main.php
Step 2: in your main.php add
<style> ... </style>
Step 3: include it as usual
<?php include 'main.php'; ?>
That is how i did it, and it works smoothly..
_trace its directory, I guess
echo css('lib/datatables_rqs/jquery.dataTables.css');

Categories