I’m using PHP handlebars templates and would like to keep all of the HTML in the template file so I don’t have a header.php but rather the handlebars looks like

<html>
  <head>
    {{#wpHead}}
  </head>

where wpHead is a helper that has nothing but wp_head(); but the output comes first before the <html> tag. I’m thinking I’ll have to use output buffering to store it as a string… Is that the only/best way?

The plan with the string is to add it to the data array that is passed to the handlebars render function:

global $post;
$data = array(
    'wpHead' => get_wp_head_as_string(),
    'postContent' => $post->post_content,
    'postContentFiltered' => apply_filters( 'the_content', $post->post_content )
);
render( 'default', $data );

And then just output it directly in the template instead of with a helper:

<html>
<head>
    <!-- other head stuff -->
    {{{wpHead}}} <!-- wp head output -->
</head>
<body>
    {{{postContentFiltered}}}
</body>

2 Answers
2

You can use PHP’s output buffering. WIth this you can write a wrapper for the get_head() function

function wpse251841_wp_head() {
    ob_start();
    wp_head();
    return ob_get_clean();
}

You can then use this as

$data = array(
    'wpHead' => wpse251841_wp_head(),
    'postContent' => $post->post_content,
    'postContentFiltered' => apply_filters( 'the_content', $post->post_content )
);

Reference: Output Control Functions

Leave a Reply

Your email address will not be published. Required fields are marked *