markdown 使用drupalSettings库将动态值从服务器(PHP)传递到客户端JavaScript

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了markdown 使用drupalSettings库将动态值从服务器(PHP)传递到客户端JavaScript相关的知识,希望对你有一定的参考价值。

The friendly.libraries.yml file will look like this:
```
friendly-greeting:
  version: 1.0
  license: GPL
  js:
    js/friendly-greeting.js: { }
  dependencies:
    - core/drupalSettings
```

We'll make use of hook_page_attachments_alter to add our asset library and our custom variables to the page.

```
/**
* Implements hook_page_attachments_alter().
*/
function friendly_page_attachments_alter(array &$page) {
  // We're going to pass along the user's display name to our front-end code.
  $account = \Drupal::currentUser();
  if ($account->isAuthenticated()) {
    // First we attach our asset library to the page.
    $page['#attached']['library'][] = 'friendly/friendly-greeting';
    // Then we pass along our dynamic value.
    // This will then be available in our JavaScript as drupalSettings.friendly.name.
    $page['#attached']['drupalSettings']['friendly']['name'] = $account->getDisplayName();
  }
}
```

 In our theme, in the js/friendly-greeting.js file we now do whatever we need to with the user's display name variable.
 ```
 (function (Drupal) {
  // If we have a nice user name, let's replace the
  // site name with a greeting.
  if (drupalSettings.friendly.name) {
    var siteName = document.getElementsByClassName('site-branding__name')[0];
    siteName.getElementsByTagName('a')[0].innerHTML = '<h1>Howdy, ' + drupalSettings.friendly.name + '!</h1>';
  }
})(Drupal);

 ```

以上是关于markdown 使用drupalSettings库将动态值从服务器(PHP)传递到客户端JavaScript的主要内容,如果未能解决你的问题,请参考以下文章

markdown 在引用中如何使用无序列表?

markdown-it基本使用

使用markdown写博客

Markdown使用小结

iOS 使用MMMarkdown 将markdown解析

MarkDown的使用简介