溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

drupal8 Adding stylesheets(css)and JavsScript(js)

發(fā)布時間:2020-08-03 17:04:02 來源:網(wǎng)絡(luò) 閱讀:954 作者:ADUJ 欄目:web開發(fā)

參考地址:https://www.drupal.org/docs/8/theming-drupal-8/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-theme
In Drupal8,stylesheets(css)and javasctipt(js)are loaded through the same system for modules(code) and themes,for everying:asset libraries.
在drupal8中加載樣式和javascript,對于module和theme通過相同的系統(tǒng),使用一切資產(chǎn)庫
Drupal use a high-level principle:assets(css or js)are still only loaded if you tell drupal it should load them.Drupal does not load every assets on every page,because it slows down front-end performance.
drupal使用高層原則:資產(chǎn)(css或js)只有在你告訴drupal的時候才會加載。drupal不會加載所有資源在頁面,這樣會降低前段性能。

Differences from drupal7

Only css,js that is required on a page will be loaded.jquery ,for example is no longer automatically loaded unless explicity specified in .libraries.yml.if your theme requires jquery or other assets you want to load on all pages,add theme in .libraries.yml.
css,js被需要的時候才加載到頁面,例如jquery不在自動加載,除非在。libaries.yml中明確指定。如果您的主題需要jquery或其他資源加載到所有的頁面,將它們添加到.libraries.yml.

The process

  1. 保存css或js文件到一個文件中,使用適當(dāng)?shù)拿s定和文檔結(jié)構(gòu)
  2. 定義一個“庫”,它可以同時包含css和js文件
  3. “attach”庫到所有的頁面,到特定的Twig模板,到一個渲染的元素通過預(yù)處理函數(shù)中。

    Defining a library

    Define all of you asset libraries in a*.libraries.yml file in you theme folder.如果我們的主題名稱是fluffiness,則文件名為fluffiness.libraries.yml.在文件中的每個“庫”都是一個詳細(xì)的css和js文件條目,like this:

    cuddly-slider:
    version: 1.x
    css:
    theme:
      css/cuddly-slider.css: {}
    js:
    js/cuddly-slider.js: {}

    在這個例子中,cuddly-slider.js文件位于你主題目錄下的js目錄中。
    記住,drupal8不在默認(rèn)加載jQuery到所有的頁面。因此,如果cuddly-slider需要jQuery,我們必須定義依賴到核心庫(Drupal core provides jQuery ,not a module or theme).定義依賴庫使用擴(kuò)展名后面跟斜線/,跟庫名,在這個例子里是core/jquery.如果其他的庫需要cuddly-slider,它應(yīng)該定義為fulffiness/cuddly-slider.不能將單獨的文件聲明為依賴庫。
    我們更新上面:

    cuddly-slider:
    version: 1.x
    css:
    theme:
      css/cuddly-slider.css: {}
    js:
    js/cuddly-slider.js: {}
    dependencies:
    - core/jquery

    大多數(shù)主題將使用一個global-stying資源庫,CSS文件被加載到每個頁面上當(dāng)主題處于激活狀態(tài)。

    global-styling:
    version: 1.x
    css:
    theme:
      css/layout.css: {}
      css/style.css: {}
      css/colors.css: {}
      css/print.css: {media: print}

    我們看到media屬性可以作為值被定義在css資源聲明的結(jié)尾。
    drupal8 Adding stylesheets(css)and JavsScript(js)

    Asset loading order 加載順序

    正如你期望的那樣,文件列出的順序是它們的加載順序。默認(rèn),所有js資源加載在頁腳footer中。
    對于重要的UI元素使用了js的,不能被顯示,除非相應(yīng)的js被運行,如果需要可以被加載到頁面header中。like this:

    js-header:
    header: true
    js:
    header.js: {}

    設(shè)置header屬性為true,表示該庫中javascript資源位于重要路徑中,并且應(yīng)該從header中加載。

    CSS properties

    以下屬性是可選的

屬性 說明 示例 補(bǔ)充
browses 基于瀏覽器加載 {IE: 'lte IE 9','!IE':false} drupal8 Adding stylesheets(css)and JavsScript(js)
group 按組進(jìn)行資源匯總。默認(rèn)是SMACS組 很少使用 /
media 媒介類型 {media: print} drupal8 Adding stylesheets(css)and JavsScript(js)
minified 資源是否已經(jīng)壓縮,默認(rèn)false {type:external,minified:true} /
preprocess 資源是否聚合,默認(rèn)true {preprocess: false} /
type 資源來源,默認(rèn)file {type:external,minified:true} /
weight 調(diào)整相對其他資源的順序(在相同的S'MASC組內(nèi)),默認(rèn)0;-50到50之間 {weight:1} /

JS properties

下面屬性是可選的

屬性 說明 示例
attributes 附加額外屬性 {type: external,attributes: {async: true}}
browsers 基于瀏覽器有條件的加載 {IE: 'lte IE 9','!IE': false}
preprocess 資源是否聚合,默認(rèn)true {preprocess: true}
type 資源來源,默認(rèn) file {type: external,minified: true}
weight 在相同的組內(nèi),調(diào)整行對其他資源的順序(setting,library,default,theme) {weigth: 1}

Overriding and extending libraries 覆蓋和擴(kuò)展庫

我們必須到.info.yml中來覆蓋.libraries.yml中定義的庫。我們既可以使用libraries-override覆蓋,也可以使用libraries-extend來擴(kuò)展。我們添加到*。info.yml的覆蓋將被子主題繼承。
libraries-override
需要使用覆蓋時的邏輯:

  1. Use the original module(or core) namespace for the library name.
  2. Use the path of the most recent override as the key.
  3. That path should be the full path to the file.
    Example
    libraries-override:
    contextual/drupal.contextual-links:
    css:
      component:
        /core/themes/stable/css/contextual/contextual.module.css: false

    contexttual/drupal.contextual-links 是核心庫的命名空間,同時/core/themes/stable/css/contextual/contextual.module.css是要覆蓋核心庫的全路徑,這里使用false進(jìn)行覆蓋
    這里需要注意的是css: 和 component: 反應(yīng)了被覆蓋庫的結(jié)構(gòu),最后一行是實際文件系統(tǒng)路徑。
    這里需要注意的是,當(dāng)被覆蓋的文件結(jié)構(gòu)發(fā)生變化,則會破會上面的路徑,這里建議使用stream wrappers.
    下面是使用librares-override的一些方式

    libraries-override:
    #替換整個庫
    core/drupal.collapse: mytheme/collapse
    #替換一個資源
    subtheme/library:
    css:
      theme:
        css/layout.css: css/my-layout.css
    #替換覆蓋stable中的資源
    contextual/drupal.contextual-toolbar:
    css:
      component:
        /core/themes/stable/css/contextual/contextual.toolbar.css: css/contextual/toolbar.css
    #替換一個核心模塊的js資源
    toolbar/toolbar:
    js:
      js/views/BodyVisualView.js: js/views/BodyVisualView.js
    #移除一個資源
    drupal/dialog:
    css:
      theme:
        dialog.theme.css: false
    #移除整個庫
    core/modernizr: false

    libraries-extend
    這對于中主題中對某些組件進(jìn)行不同的設(shè)計是完美的,同時不會應(yīng)用到全局css中,即自定義組建外觀,而無需在每個頁面上加載css

    #擴(kuò)展drupal.user庫,從d8dev的baidu-map庫添加資源
    libraries-extend:
    fulffiness/drupal.user:
    - d8dev/baidu-map #主題名|模塊名/庫名

    Attaching libraries to page(s) 添加庫到頁面

    我們加載的某些庫可能并不是所有頁面都需要。為了獲得更快的性能,請不要在沒有使用庫的地方加載它們。以下是如何選擇性加載庫的示例

    Attaching a library via a Twig templage 通過Twig模板加載庫

    attach_library()函數(shù)可以在任何*.html.twig使用,如:

    {{attach_library('fulffiness/cuddly-slider')}}
    <div>Some fluffy markup {{message}}</div>

    Attaching a library to all pages:

    要將庫添加到使用主題的所喲頁面,請在主題的*.info.yml文件中的libraries關(guān)鍵字生命如下:

    name: Example
    type: theme
    core: 8.x
    libraries:
    - fulffiness/cuddly-slider

    在編輯.info.yml或者.libraries.yml文件后,記得要清除緩存

    Attaching a library to a subset of pages

    在某些情況下,您不需要您的庫對所有頁面有效,只適用于頁面的子集。例如:只顯示某個區(qū)塊時,或在顯示某個節(jié)點類型時
    主題可以通過在THEMENAME.theme文件(在主題的根目錄下)中實現(xiàn)THEME_preprocess_HOOK()函數(shù)來實現(xiàn),使用主題的機(jī)器名替換“THEME”,使用主題鉤子名稱的機(jī)器名替換“HOOK”.
    例如,如果你想把JavaScript附件到maintenance page(maintenance-page.html.twig),那么“HOOK”部分就是“maintenance_page”,函數(shù)看起來如下:

    <?php
    function fulffiness_preprocess_maintenance_page(&$variables){
    $variables['#attached']['library'][] = 'fulffiness/cuddly-slider';
    }

    你可以為其他主題鉤子做類似的事情,當(dāng)然你的函數(shù)也可以有邏輯,比如監(jiān)測在“block”鉤子中預(yù)處理那個區(qū)塊,“node”鉤子中處理是那個節(jié)點類型。
    重要提示!在這種情況下,您需要指定與您的條件相對應(yīng)的緩存性元數(shù)據(jù)!最常見的例子,基于當(dāng)前路徑由附加某個庫的情況:

    <?php
    function fulffiness_preprocess_page(&$variables){
    $variables['page']['#cache']['context'][] = 'route';
    if(\Drupal::routeMatch()->getRouteName() === 'entity.node.preview'){
        $variables['#attached']['library'][] = 'fulffiness/mode-preview';
    }
    }

    Attaching configurable JavaScript 添加可配置的js

    在某些情況下,您可能需要將JavsScript添加到依賴于一些計算PHP信息的頁面上。
    In this case,create a JavaScript file,define and attach a library just like before,but also attach JavaScript setting and have that JavsScript file read those settings, via drupalSettings. However,to make drupalSettings available to our JavaScript file, we have to do the same works as we had to do make jQuery available:we have to declare a dependency on it.
    這樣就變成:

    cuddly-slider:
    version: 1.x
    js:
    js/cuddly-slider.js: {}
    dependencies:
    - core/jquery
    - coer/drupalSettings
    - core/drupal

    <?php
    function fulffiness_page_attachments_alter(&$page){
    $page['#attached']['library'][] = 'fluffiness/cuddly-slider';
    $page['$attached']['drupalSettings']['fluffiness']['cuddlySlider']['foo'] = 'bar';
    }

    這里的‘bar’是一個計算的值(注意清除緩存)
    然后cuddly-slider.js可以訪問drupalSettings.fluffiness.cuddlySlider.foo( and it will === 'bar' ):

    (function($,Drupal,drupalSettings){
    'use strict';
    Drupal.hehaviors.mybehaviror = {
        console.log( drupalSettings.fulffiness.cuddlySlider.foo );
    }
    })(jQuery,Drupal,drupalSettings);

    Adding attribrutes to script elements 為script標(biāo)簽添加屬性

    Example:

https://maps.googleapis.com/maps/api/js?key=myownapikey&signed_in=true&libraries=drawing&callback=initMap:
  type: external
  attributes:
    defer: true
    async: true
    data-test:map-link

結(jié)果為:


<script src="https://maps.googleapis.com/maps/api/js?key=myownapikey&signed_in=true&libraries=drawing&callback=initMap" async defer data-test="map-link"></script>

CDN/externally hosted libraries CDN/外部托管庫

你可能希望使用外部CDN上的JavaScript-如網(wǎng)頁字體庫通常使用URL。這可以通過聲明為外部庫(type:external)來完成。

angular.angularjs:
  remote: https://github.com/angular
  version: 1.4.4
  license:
    name: MIT
    url: https://github.com/angular/angular.js/blob/master/LICENSE
    gpl-compatible: true
  js:
    https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.min.js: { type: external, minified: true }

Inline JavaScript

(不推薦使用內(nèi)聯(lián)樣式,故沒有主要測試)

內(nèi)聯(lián)JavsScript是非常不鼓勵的。建議將內(nèi)聯(lián)js放在一個文件中。這樣可以緩存js,也可以被刪除和檢查。

Inline JavsScript that generates markup

你想把它們放在一個自定義的區(qū)塊或一個Twig模板中
Example:


<script type="text/javascript"><!--
ad_client_id = "some identifier"
ad_width = 160;
ad_height = 90;
//--></script>
<script type="text/javascript" src="http://adserver.com/ad.js"></script>

Inline JavaScript that affects the entire page

Using any inline JavsScript is highly discouraged.

Inline JavaScript that is in integration module 內(nèi)嵌在集成模塊中

Differences with Drupal7

  1. hook_library_info()被替換為*.libraries.yml
  2. 在drupal8中drupal_add_css()、drupal_add_js()、drupal_add_library()被移除,推薦使用#attached

上面是結(jié)合本人自己的理解整理的,如有錯誤請多多指教;其中也有些不甚明了的地方,請給予指正。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI