Why is this if statement not working in twig?
题
It's a bidirectional D9 site where I removed dir=rtl from my theme's html.html.twig with an if statement and it's working fine. I did that to avoid an MS browsers bug ignoring position: sticky in css if there was any dir="rtl" in either html or body tags. I did so in html.html.twig with this code:
{% if html_attributes['dir'] == 'rtl' %}
<html{{ html_attributes|without('dir') }}>
{% elseif html_attributes['dir'] == 'ltr' %}
<html{{ html_attributes }}>
{% endif %}
So now, when the site is in English (or any LTR lang) the html tag has a dir="ltr" attribute in it but none if the dir is rtl. That's working well.
I added the dir attribute to page.html.twig #page-warpper like this:
{% apply spaceless %}
{% if html_attributes['dir'] == 'ltr' %}
<div id="page-wrapper" dir="ltr">
{% else %}
<div id="page-wrapper" dir="rtl">
{% endif %}
{% endapply %}
<div id="page"> ......
This isn't working. Only the rtl direction is applied to the #page-wrapper regardless of the site's direction/ language. I added the spaceless filter later as I thought it might be an indentation issue but no change still.
I also tried this but not working either:
{% if html_attributes['dir'] %}
<div id="page-wrapper" dir="ltr">
{% else %}
<div id="page-wrapper" dir="rtl">
{% endif %}
Thank you for any views. And sure, I did drush cr after each twig edit.
解决方案
The variable html_attributes
is not available in a page template. To make it available copy this code from template_preprocess_html() to your page preprocess hook:
use Drupal\Core\Template\Attribute;
/**
* Implements hook_preprocess_page().
*/
function mytheme_preprocess_page(&$variables) {
$variables['html_attributes'] = new Attribute();
$language_interface = \Drupal::languageManager()->getCurrentLanguage();
$variables['html_attributes']['lang'] = $language_interface->getId();
$variables['html_attributes']['dir'] = $language_interface->getDirection();
}