Drupal 8站点:如何显示城市与邮政编码及自定义地址模板?
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.twigtemplate in the Address module’stemplatesdirectory. - Copy this file into your active theme’s
templatesfolder. If you only want to target addresses used in the Profile module, rename it toaddress-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

