1

I'm trying to inject data of "render-to-html" route in handlebars js template to render HTML response in fast API here is a minimal example of it. or is there any way to make this possible using other templating engine?

@app.get("/render-to-html")
def read_item(first_name:str,last_name:str,fav_lang:str,exp:int):
    result = {
  "user": [
    {
      "first_name": first_name,
      "last_name": last_name
    },
    {
      "fav_lang": fav_lang,
      "experience": exp
    }
  ]
}
   #return htmlresponse
   # how to inject this result into context of index.html and return html response
 

here is the index.html

<!DOCTYPE html>
<html>
  <head>
    <!--CDN https://handlebarsjs.com/installation/#cdns -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.7.7/handlebars.js"></script>
  </head>
  <body>
    <div id="contentDiv"></div>

    <script id="entry-template" type="text/x-handlebars-template">
      <div class="entry">
        {{#if user}}
          {{#each user}}
          <ul>
             <li> {{first_name}}</li>
             <li> {{last_name}}</li>
          </ul>
          {{/each}}
        {{/if}}
      </div>
    </script>

    <script type="text/javascript">
      // Assign the template name
      var source = document.getElementById("entry-template").innerHTML;
      var template = Handlebars.compile(source);

      // Compile the template
      var context = {
        // Response from the API
      };
      var templateData = template(context);

      document.getElementById("contentDiv").innerHTML += templateData;
    </script>
  </body>
</html>

To return index.html in "/render-to-html" route

  • Related answers can also be found [here](https://stackoverflow.com/a/73440556/17865804), as well as [here](https://stackoverflow.com/a/73726553/17865804) and [here](https://stackoverflow.com/a/73264904/17865804). – Chris Nov 05 '22 at 10:24

0 Answers0