且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从外部api填充树枝模板

更新时间:2022-10-15 08:53:12

在Drupal 7这是可能的,但是一个糟糕的设计,把任意PHP放入模板。在Drupal 8中,很难做到有意思。您不应该尝试在您的Twig文件中执行任意PHP,或者在处理请求时进行远程API调用。



您应该调用API并收集数据 你到达树枝。您应该创建一个处理该API交互的自定义​​模块,并将响应放置在字段,块或其他结构中,以便在适当的上下文中呈现(通常,自定义块对于这样的事情有效,但确切地说,哪种方法最有意义取决于你的项目)。您还应该记住,任何需要远程API调用的页面可能都很慢,除非该API调用非常简单,而且非常快。 BigPipe模块可以帮助您解决这些速度问题,但需要额外的学习曲线。



如果您希望浏览器处理API调用,您将需要创建一个div(或类似的标记)放置结果,并将JavaScript附加到结构中,并在大部分页面加载完成后进行实际的API调用。



至于安全性:它和你一样安全。 Drupal将提供一些帮助,以避免最常见的安全错误,但您仍然可以执行不安全的操作(例如,与不受信任的第三方共享数据或假定响应数据始终是安全的)。


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.

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).