我正在尝试使用以下方法创建 drupal 表单建议:
function pfe_theme_suggestions_form_alter(array &$suggestions, array $variables) {
$suggestions[] = 'form__'. $variables['element']['#id'];
}
Run Code Online (Sandbox Code Playgroud)
但在创建form--user-login-form.html.twig后,drupal 不会考虑此模板,但它始终使用form.html.twig。
这是 html 注释:
<!-- THEME DEBUG -->
<!-- THEME HOOK: 'form' -->
<!-- FILE NAME SUGGESTIONS:
* form--user-login-form.html.twig
x form.html.twig
-->
<!-- BEGIN OUTPUT from 'core/themes/stable/templates/form/form.html.twig' -->
Run Code Online (Sandbox Code Playgroud)
添加 HOOK_theme() 后:
function pfe_theme_suggestions_form_alter(array &$suggestions, array $variables) {
$suggestions[] = 'form__'.$variables['element']['#id']; //form--user-login-form.html.twig
}
function pfe_theme($existing, $type, $theme, $path) {
return [
'form__user-login-form' => [
'#theme' => 'form--user-login-form',
'render element' => 'form',
],
];
}
Run Code Online (Sandbox Code Playgroud)
我收到此错误:
Twig_Error_Loader:模板“themes/pfe/templates/form--user-login-form.html.twig”未定义(Drupal\Core\Template\Loader\ThemeRegistryLoader:无法找到模板“themes/pfe/templates/form- -user-login-form.html.twig”在 Drupal 主题注册表中。)。在 Twig_Loader_Chain->getCacheKey() 中(/home/marwen/workspace/pfe/themes/pfe/templates/block/block--userlogin.html.twig 第 43 行)。
小智 4
使用“str_replace”将“-”替换为“_”,例如:
$suggestions[] = 'form__' . str_replace('-','_', $variables['element']['#id']);
Run Code Online (Sandbox Code Playgroud)