Populate twig template from external api

2019-09-03 02:57发布

问题:

I am building a Drupal 8 site and am new to the twig templating engine. For one specific content type I would like to make a call to an external restful api and render some of the returned data as fields in the twig template.

I have an internal id to call out to the API and I would like to embed in the template:

  • The api call
  • set a number of variables from the call
  • render the result (with some logic if it does not exist)

Is this something that is easy to do with twig and drupal 8? As a secondary question, is this secure?

The alternative at this stage is to write small Drupal 8 module but as there is no user input on the page, just rendering from the returned api call, I thought it would be easier to have it all in one place.

回答1:

In Drupal 7 it was possible, but a poor design, to put arbitrary PHP into the template. In Drupal 8 it was made hard to do intentionally. You should not attempt to execute arbitrary PHP in your Twig files or make remote API calls that late in the processing of a request.

You should call the API and gather the data before you reach twig. You should create a custom module that handles that API interaction and places the response in a field, block, or another structure for rendering in the appropriate context (often a custom block works well for things like this, but exactly which approach makes the most sense depends on your project). You should also keep in mind that any page requiring a remote API call is likely to be slow unless that API call is very simple and very very fast. The BigPipe module can help you address those kinds of speed issues, but involve an additional learning curve.

If you want the browser to handle the API call, you will want to create a div (or similar markup) to place the results, and attach the JavaScript to the structure and make the actual API call after most of the page load is complete.

As for security: it is as secure as you make it. Drupal will provide some help to avoid the most common security mistakes, but you can still do things that would make it insecure (like sharing data with an untrusted third party or assuming the response data is always safe).