TYPO3 StandaloneView未找到模板:指定TemplateRootPath被忽略
问题现象
使用StandaloneView输出数据时,指定的TemplateRootPath被忽略,TYPO3抛出异常,提示在/typo3/public/typo3conf/ext//Resources/Private/Templates/路径下查找模板,但实际设置的TemplateRootPath是该路径下的/printView/子文件夹。
问题代码
$standaloneView = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\TYPO3\CMS\Fluid\View\StandaloneView::class); $standaloneView->setLayoutRootPaths([ \TYPO3\CMS\Core\Utility\GeneralUtility::getFileAbsFileName('EXT:<my-extension>/Resources/Private/Layouts/printView/'), ]); $standaloneView->setPartialRootPaths([ \TYPO3\CMS\Core\Utility\GeneralUtility::getFileAbsFileName('EXT:<my-extension>/Resources/Private/Partials'), ]); $standaloneView->setTemplateRootPaths([ \TYPO3\CMS\Core\Utility\GeneralUtility::getFileAbsFileName('EXT:<my-extension>/Resources/Private/Templates/printView/'), ]); $standaloneView->setFormat('html'); $standaloneView->setTemplate('printView/printView'); $standaloneView->assignMultiple([ //variable assignment ]); echo $standaloneView->render();
<my-extension>为实际扩展key占位符
问题原因
setTemplate('printView/printView')的参数错误。已经通过setTemplateRootPaths将模板根路径指向了Templates/printView/,此时再传入printView/printView,会让系统尝试在Templates/printView/printView/下查找模板,该路径不存在时,系统会回退到默认模板根路径,导致出现报错路径。
解决方法
修正模板名称参数
将setTemplate的参数改为模板文件名(不含格式后缀),因为模板根路径已经指向了printView子文件夹:$standaloneView->setTemplate('printView');需确保
printView.html文件存在于EXT:<my-extension>/Resources/Private/Templates/printView/目录下。验证路径正确性
可先打印getFileAbsFileName的返回结果,确认路径是否正确指向目标文件夹:$templateRootPath = \TYPO3\CMS\Core\Utility\GeneralUtility::getFileAbsFileName('EXT:<my-extension>/Resources/Private/Templates/printView/'); var_dump($templateRootPath);若路径为空或错误,检查扩展key是否正确、路径拼写是否有误。
可选:调整路径与模板名的组合
如果希望保留setTemplate('printView/printView'),则需将TemplateRootPath设置为上层的Templates/目录:$standaloneView->setTemplateRootPaths([ \TYPO3\CMS\Core\Utility\GeneralUtility::getFileAbsFileName('EXT:<my-extension>/Resources/Private/Templates/'), ]);这种方式下,系统会正确找到
Templates/printView/printView.html文件。
内容的提问来源于stack exchange,提问作者Starzi

