官术网_书友最值得收藏!

The Token API

Tokens in Drupal are a standard formatted placeholder, which can be found inside a string and replaced by a real value extracted from a related object. The format tokens use is type:token, where type is the machine-readable name of a token type (a group of related tokens), and token is the machine-readable name of a token within this group.

The power of the Token API in Drupal is not only given by its flexibility but also by the fact that it is already a popular API. It is flexible because you can define groups, which contain related tokens, linked by the data object that contains their value (for example, a Node object or User object). It is popular because in previous versions of Drupal, it was the contributed module many others were dependent on to define their own tokens, and it is now available in Drupal 8 core with many tokens already defined out of the box. So, you'll find many existing tokens that you can use in your code, and if not, you can define your own.

There are three main components of this API--at least from the point of view of a Drupal 8 module developer. These components are two hooks--hook_token_info() and hook_tokens()--and the Token service, which is used to perform the replacement.

The first hook is used to define one or more token types and tokens. It essentially registers them with the system. The second is fired at the moment a token is found inside a string (a replacement is attempted by the service) and is used to do the replacement of the tokens based on the data that is passed to it from the service. For example, the User module defines two token types and a number of tokens inside hook_token_info(). Inside hook_tokens(), it checks whether the token is one of its own and tries to replace it with the contextual data (either a User object or the currently logged-in User object). To read the documentation related to each of these in detail and to see an extended example, you can find them either on the Drupal.org API page or inside the token.api.php file. There, you will also find alter hooks that correspond to these two and can be used to alter either the defined token information or logic to replace these tokens written by other modules or Drupal core.

The Token service is what you can use as module developers if you have to replace tokens found inside a string. We will see how this is used in the next section.

主站蜘蛛池模板: 龙胜| 咸阳市| 基隆市| 普洱| 木兰县| 皮山县| 仙桃市| 呈贡县| 淮安市| 德庆县| 阜新市| 民乐县| 恩施市| 手游| 盘山县| 阿拉善右旗| 三门县| 涟源市| 东宁县| 武平县| 五指山市| 邵阳县| 金堂县| 高要市| 谷城县| 阳高县| 丽江市| 犍为县| 新化县| 旅游| 永寿县| 四子王旗| 吴桥县| 乌兰县| 永吉县| 海晏县| 新乡市| 江口县| 聂拉木县| 柞水县| 安阳市|