You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Drupal 8站点:如何显示城市与邮政编码及自定义地址模板?

Customizing Address Template in Drupal 8 to Display City & Postal Code

Hey there, let's walk through how to tweak your Address module template to show city and postal code alongside your existing address fields. Here's what you need to do:

Step 1: Override the Address Template File

First, you’ll want to create a custom template in your theme to avoid modifying the module’s core files (which would get overwritten during updates):

  • Locate the default address-plain.html.twig template in the Address module’s templates directory.
  • Copy this file into your active theme’s templates folder. If you only want to target addresses used in the Profile module, rename it to address-plain--profile.html.twig (this uses Drupal’s template suggestion system to apply changes only to Profile-related addresses).

Step 2: Modify the Template to Include City & Postal Code

Open the copied template file. You’ll see the existing variables listed in the comment block—we need to add the locality (city) and postal_code variables where you want them to appear. Here’s an example of an updated template:

{# /**
 * @file
 * Custom template for the 'plain' address formatter (Profile-specific).
 *
 * Available variables:
 * - given_name: Given name.
 * - additional_name: Additional name.
 * - family_name: Family name.
 * - organization: Organization.
 * - address_line1: First address line.
 * - address_line2: Second address line.
 * - locality: City/locality.
 * - postal_code: Postal code.
 * - administrative_area: State/province.
 * - country_code: ISO 3166-1 alpha-2 country code.
 */ #}

{% if given_name or additional_name or family_name %}
  {{ given_name }} {% if additional_name %}{{ additional_name }} {% endif %}{{ family_name }}<br>
{% endif %}
{% if organization %}
  {{ organization }}<br>
{% endif %}
{% if address_line1 %}
  {{ address_line1 }}<br>
{% endif %}
{% if address_line2 %}
  {{ address_line2 }}<br>
{% endif %}
{# Add city and postal code section #}
{% if locality %}
  {{ locality }}
  {% if postal_code %}, {{ postal_code }}{% endif %}<br>
{% elseif postal_code %}
  {{ postal_code }}<br>
{% endif %}
{% if administrative_area %}
  {{ administrative_area }}<br>
{% endif %}
{% if country_code %}
  {{ country_code }}
{% endif %}

Step 3: Clear Drupal’s Cache

Don’t skip this step! Head to Configuration > Performance > Clear all caches so Drupal recognizes your new template.

That’s it—your address displays will now include city and postal code exactly where you placed them in the template.

内容的提问来源于stack exchange,提问作者Mathieu61

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:41:51