如何防止TYPO3在输出JSON时渲染head-和body-elements?

How to prevent TYPO3 to render head- and body-elements when outputting JSON?

在 TYPO3 8.7 中,我尝试使用 FLUID 生成 JSON。

我创建了一个包含虚拟内容的页面,并更新了文件夹中所有页面的 TypoScript 配置。

TypoScript 设置

[PIDinRootline = 10]
    page = PAGE
    page {
        typeNum = 0

        config {
            disableAllHeaderCode = 1
            disablePrefixComment = 1
            xhtml_cleaning = none
            admPanel = 0
            debug = 0
            metaCharset = utf-8
            additionalHeaders = Content-Type:text/json;charset=utf-8
        }
    }
[global]

我还创建了一个虚拟 JSON 文件,以测试输出,然后再使用 FLUID 创建实际内容:

api.json

{
    "hello": "world"
}

现在,这似乎工作正常。但是输出仍然包含 html- 和 body- 元素。

渲染输出:

<html>
    <head></head>
    <body>
        {"hello": "world"}
     </body>
</html>

documentations says:

If you want to output JSON, RSS or similar data with Fluid, you have to write the appropriate TypoScript which passes the page rendering to Extbase and Fluid respectively. Otherwise, TYPO3 will always generate the <head>- and <body>-section.

但我实际上不知道在这里做什么。我怎样才能让 TYPO3 不渲染包装 HTML-elements?

当您覆盖页面对象时,您应该在 page > 之前删除其中的所有内容。 另外,Fluid 是 HTML 的模板引擎,我不知道它是否适合 JSON 输出。

更好的方法:
我建议使用一个单独的对象而不是页面和不同的页面类型:

[globalVar = GP:type = 133]
  jsonOutput = PAGE
  jsonOutput {
    typeNum = 133

    config {
      ...
    }
  }
[global]

你错过的是这个打字错误:

config.disableAllHeaderCode = 1

read the manual

如果您希望在特殊页面上使用它,您可以为此页面使用特殊的错字模板。对于页面类型,它稍微复杂一些,因为此配置适用于所有页面类型。
如果你只想要一些 config 选项用于特殊的页面类型,你可以将此配置添加到页面类型中,如下所示:

json = PAGE
json.config.disableAllHeaderCode = 1

请注意,如果您输出 HTML 以外的其他结构,则流体会更加复杂。但这是可能的!特别注意空格和大括号 ({})

问题出在 TYPO3 8 及更新版本中的新语法。在较新的版本中,additionalHeaders 不再只是一个 TEXT,而是一个 array with numeric indices。所以要设置正确的 header 类型,你必须使用这个:

additionalHeaders.10.header = Content-Type:application/json;charset=utf-8