1、使用{{ now|date('Y') }}获取当前年份。date()中的参数参照:https://www.php.net/manual/zh/datetime.format.php
2、在node.html.twig中,可以使用{{ node.created.value|date('jS M Y') }}可以获取当前文章的发布日期。date()中的参数参照:https://www.php.net/manual/zh/datetime.format.php
3、在模板中使用{{ directory }}获取当前主题路径,比如themes/custom/your_theme_name
4、限制输出字符长度(在node.html.twig中)
<!-- 限制文章标题字数 -->
<a href="{{ url }}">{{ label|render|striptags|slice(0, 36) ~ '...' }}</a>
<!-- 限制文章摘要字数 -->
{{ content.body|render|striptags|slice(0, 100) ~ '...' }}5、在文章内容页显示文章阅读数量。
首先要启用Statistics模块。然后在.theme文件中添加如下代码:
function themename_preprocess_node(&$variables) {
if (isset($variables['node'])) {
$nid = $variables['node']->id();
$statistics = \Drupal::service('statistics.storage.node')->fetchView($nid);
if (is_object($statistics)){
$variables['view_count'] = $statistics->getTotalCount() ?? 0;
}else{
$variables['view_count'] = "0";
}
}
}在模板中显示阅读数量,例如,在node--full.html.twig模板中:
{% if view_count %}
阅读:{{ view_count }}
{% endif %}6、在模板中获取当前路由
function themename_preprocess_page(&$variables) {
$route_name = \Drupal::routeMatch()->getRouteName();
$variables['route'] = $route_name;
}在模板中调用{{ route }}
在模板中判断:
{% if route == 'user.login' %}
这是用户登录页
{% elseif route == 'user.register' %}
这是用户注册页
{% endif %}7、在模板中判断用户登录状态并显示用户名。
{% if logged_in %}
你好, {{ user.account.name }}{# 显示当前登录用户的用户名 #}
<a href="/user/logout">退出</a>{# 显示退出链接 #}
{% else %}
请登录...
{% endif %}