shinve — 2012-02-23T18:45:33-05:00 — #1
I know the title of the post is a bit vague, but I did not know how to best phrase this.
I want the title of a page, which is in something like "header.php" to be determined by something that comes later in the code, like something in "content.php". In particular, I am trying to make the title of a page dynamically generated, through something like:
<title><?php echo $title ?></title>
But this yields an undefined variable if I assign something to title AFTER this line of code on a page. I'd appreciate any solutions or best practices to use when handling with this issue.
wonshikee — 2012-02-23T19:37:03-05:00 — #2
There's simply no way for you to do it.
The proper method, is to process all the values before the HTML.
It's called separation of logic and view.
I'm guessing you have something like
<body><?php include 'content.php' ?></body>
In which case there's not really an easy solution, except to rewrite the logic so it's processed (and hold the data in a variable) before the <html>. Then within content.php, you would simply output the processed variable instead of doing the logic there. This is the essence of a template system.
scallioxtx — 2012-02-24T00:28:42-05:00 — #3
Alternatively you could use output buffering. Very rough example:
$title = 'This is the HTML title!';
echo 'Hello world!';
<title><?php echo $title; ?></title>
<?php echo $content; ?>
$content = ob_get_clean();
Basically this will first execute the file view.php (which sets $title) and store the result in $content. The variable $content can then be used in the template.php.
Again, the example is very rough but I hope you get the idea. If not I'd be happy to elaborate
shinve — 2012-02-25T10:04:56-05:00 — #4
I think that's enough for me to go on for now. I will come back here if I need more help. Thanks.