表示ラベルへのアクセス

範囲設定されたモジュール @salesforce/label から表示ラベルをインポートします。カスタム表示ラベルは、サポートされる言語に翻訳できる、Salesforce に保存されているテキスト値です。カスタム表示ラベルを使用すると、情報 (ヘルプテキストやエラーメッセージなど) をユーザの母国語で表示する多言語アプリケーションを作成できます。

1import labelName from "@salesforce/label/labelReference";
  • labelName — 表示ラベルを参照する名前。
  • labelReference — 組織の表示ラベルの名前。形式は namespace.labelName です。この形式が使用されるのは、Visualforce やその他の Salesforce テクノロジの管理パッケージで使用される形式と同じであるからです。これと同じ形式を使用すると、アクセス元の場所にかかわらず、表示ラベル myns.labelName にアクセスできます。

次のサンプルコードでは、2 つの表示ラベルがインポートされます。

1// labelExample.js
2import { LightningElement } from "lwc";
3
4// Import the URL for the static resource named 'salesforceLogo'
5import SALESFORCE_LOGO from "@salesforce/resourceUrl/salesforceLogo";
6
7// Import custom labels
8import greeting from "@salesforce/label/c.greeting";
9import salesforceLogoDescription from "@salesforce/label/c.salesforceLogoDescription";
10
11export default class LabelExample extends LightningElement {
12  // Expose the static resource URL to use in the template.
13  logoUrl = SALESFORCE_LOGO;
14
15  // Expose the labels to use in the template.
16  label = {
17    greeting,
18    salesforceLogoDescription,
19  };
20}

テンプレートで表示ラベルを使用するには、JavaScript プロパティを参照するときに使用したのと同じ {property} 構文を使用します。

1<!-- labelExample.html -->
2<template>
3  <c-page-header
4    header="Using static resources and custom labels"
5    description="This sample shows how to reference external items like static resources and custom labels"
6  ></c-page-header>
7
8  <c-card>
9    <img src={logoUrl} alt={label.salesforceLogoDescription} width="100" /><br />
10    <br />
11    {label.greeting}
12  </c-card>
13</template>

Salesforce DX プロジェクトの場合、表示ラベルのファイルは、force-app/main/default のどのサブディレクトリにでも配置できます。たとえば、ExampleLabels.labels-meta.xml という名前のこのファイルは force-app/main/default/mylabels に配置されます。

1<?xml version="1.0" encoding="UTF-8"?>
2<CustomLabels xmlns="http://soap.sforce.com/2006/04/metadata">
3    <labels>
4        <fullName>quoteManual</fullName>
5        <value>This is a manual quote.</value>
6        <language>en_US</language>
7        <protected>false</protected>
8        <shortDescription>Manual Quote</shortDescription>
9    </labels>
10    <labels>
11        <fullName>quoteAuto</fullName>
12        <value>This is an automatically generated quote.</value>
13        <language>en_US</language>
14        <protected>false</protected>
15        <shortDescription>Automatic Quote</shortDescription>
16    </labels>
17</CustomLabels>

関連トピック

The Japanese Summer '24 guide is now live

日本語の Summer '24 ガイドが公開されました! 「Component Reference (コンポーネントリファレンス)」は、以前と同様にコンポーネントライブラリにあります。