Jump to content

Using str_replace() content ends up in improper place


coffejor

Recommended Posts

I'm creating a template engine to replace placeholder strings in my html template with dynamic content served by a function. To do this I have written the following template processor:

 

<?php
function load_template()
{
    $template_file = "template.html";
    $template = file_get_contents($template_file);
    $template_vars = array('{MAIN}', '{NAV}', '{TITLE}');
    $template_vals = array(bodyContent(), navContent(), $title);

    function template_eval (&$template, &$template_vars, &$template_vals)
    {
        return str_replace($template_vars, $template_vals, $template);
    }

    echo template_eval($template, $template_vars, $template_vals);
}

load_template();
?>

 

which is called by a page like so:

 

<?php
$title = "Example Title";

function navContent()
{
?>
                    <h1>Page Links:</h1>
                    <ul>
                        <li><a href="">Link 1</a></li>
                        <li><a href="">Link 2</a></li>
                        <li><a href="">Link 3</a></li>
                    </ul>
<?php
}

function bodyContent()
{
    ?>

                    <h1>Example Title 1</h1>
                    <p>Example Content 1</p>
                    <h1>Example Title 2</h1>
                    <p>Example Content 2</p>
                    <h1>Example Title 3</h1>
                    <p>Example Content 3</p>
<?php
}

    require_once (URL."/test_templateProcessor.php");
?>

 

Unfortunately, the content fails to be placed into the appropriate place in the template but, rather, ends on top of the template as can be seen here: http://www.jordancoffey.com/test_index.php.

 

I'm not quite sure why it does this, so any insight would be greatly appreciated. Thanks in advance for any and all help!

 

Jordan

you need to return the content in your functions. as written, they will output the content to the page. something more like this:

 

function navContent()
{
                    return "<h1>Page Links:</h1>
                    <ul>
                        <li><a href=''>Link 1</a></li>
                        <li><a href=''>Link 2</a></li>
                        <li><a href=''>Link 3</a></li>
                    </ul>";
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.