SSR: Dynamically inject HTML content into index.html



  • I am building an SSR/SPA application where I need to dynamically inject some HTML content above and below the #q-app div element when the page is rendered on the server. (This content is pulled from snippet files stored on the server and is specific to the incoming web requests.)

    I tried using a boot file, following the example given at the bottom of the Configuring SSR page:

    // some boot file
    export default ({ app, ssrContext }) => {
      ssrContext.someProp = '<div>This is a header</div>'
    }
    
    <!-- index.template.html -->
    <% if (htmlWebpackPlugin.options.ctx.mode.ssr) { %>{{ someProp }} <% } %>
    

    However, this results in escaped content appearing in the resulting page:

    <body class="desktop no-touch body--light" >
        &lt;div&gt;This is a header&lt;/div&gt;
        <!-- DO NOT touch the following DIV -->
        <div id="q-app"></div>
    </body>
    

    It is important for this content to be correctly rendered on the server, so having an onload event that ‘unescapes’ the content on the client side is not suitable. Having researched htmlWebpackPlugin a bit and discovering that it uses lodash’s template function under the covers, I can’t find a way to prevent the escaping.

    Consequently, I am wondering if an App Extension of some kind would allow me to manipulate the index.html file before returning it. So far, I have not found what seems to be a viable approach for this from reading the App Extension documentation though. Any advice or suggestions, much appreciated. Am happy to do further research if somebody can point me in the right direction!



  • @rixybix

    Sounds like you are almost there with your current method.
    Maybe this helps:

    Thus with htmlWebpackPlugin :
    <%= Outputs the unescaped value into the template
    <%- Outputs the escaped value into the template

    https://stackoverflow.com/questions/57262244/output-raw-html-in-ejs-templates-with-htmlwebpackplugin


Log in to reply