phptemplatesvarnishesi

How to use Varnish ESI with modular PHP templating system


I am looking to implement varnish into a data heavy/user-centric website. How do I setup ESI using a system which uses php to include html templates?

I currently use a custom php templating system (similar to an MVC design pattern) which works like this:

make page request -> php calculates logic -> php includes html template pages and fills out variables -> page is output

I've only ever seen esi tags used in predominantly html pages, to include php snippets.

like the code below:

<HTML>
<BODY>
The time is: <esi:include src="/php-includes/date.php"/>
at this very moment.
</BODY>
</HTML>

But can it be done the other way around? e.g. esi tags in php pages to include html snippets?

Similar to this:

<?php
//logic here
$content = "this will be displayed on the content page"

include("templates/header.html.php"); //esi would go here since page is static content
include("templates/content.html.php"); //no esi here, since page is dynamic content
include("templates/footer.html.php"); //esi would go here since page is static content
?>

Solution

  • You just have to create a kind of "ESI" renderer thingy for your specific MVC implementation, as in /esi.php?template=foo, then inside something like:

    ... whatever you need to boostrap your app in order to render a template ....
    include("templates/$template.html.php");
    .... exit so no header/fooder stuff is rendered, only template HTML of interest
    

    Surely not as simple as that but in a nutshell a similar thing.

    I would then put some logic atop each template file to emit either the HTML (if rendered by esi.php or if ESI "feature" is in disabled state) or <esi tag only.

    So for example templates/header.html.php could have (pseudo-code):

    if esi (detect by checking request_uri to be esi.php) then echo '<esi /esi.php?template=header?somevar-from-parent=...'; return
    ---existing code--