Blogs
Liferay DXP本身帶有一個Carousel的範本,但是這個範本使用的是舊的AUI的範本。現在因為Liferay DXP是基於Lexicon和Bootstrap 3的,創建一個響應式的圖片播放非常簡單。
基本需求:
- 圖片播放基本功能
- 螢幕尺寸變化後,圖片不變型
- 修改圖片不需要修改代碼
- 不需要部署外掛程式
- 可複用
分析:
- 可以利用Bootstrap 3的carousel外掛程式實現圖片播放基本功能(https://www.w3schools.com/bootstrap/bootstrap_carousel.asp)
- 可以利用Lexicon的Image Aspect Ratios保持圖片的長寬比(http://liferay.github.io/lexicon/content/images-and-thumbnails/#image-aspect-ratios)
- 可以利用Web Content來實現內容存儲和範本化,同時可複用。
- 不需要額外的OSGi外掛程式開發。JSON格式的structure和FTL格式的範本移植起來很容易。
1. 創建Web Content Structure
可以簡單的創建一個web content structure。其中包含一個文本欄位,用於設置長寬比,一個可重複的圖片欄位。
2. 創建對應的範本
我們可以直接為剛剛創建好的carousel structure創建一個範本。
3. 定義圖片長寬比
參考Lexicon的文檔,可以通過css為圖片播放定義一個固定的長寬比。在我這裡,長寬比可以通過structure設置,針對移動設備回應式的比例為了簡單,我就直接寫在範本中了。
<style> #carousel-${request.get("portlet-namespace")} .aspect-ratio-custom { padding-bottom: ${aspectRatio.getData()}; } @media (max-width: 799px) { #carousel-${request.get("portlet-namespace")} .aspect-ratio-custom { padding-bottom: 67%; } } </style>
4. 實現Bootstrap的carousel和Lexicon的固定比例
可以直接參考Bootstrap的carousel的實現方式寫HTML,CSS,並且通過freemarker迴圈寫入圖片。在圖片所在的div中定義class為aspect-ratio和aspect-ratio-custom。
<#if image.getSiblings()?has_content> <section class="carousel-container"> <div class="carousel slide" data-ride="carousel" id='carousel-${request.get("portlet-namespace")}'> <ol class="carousel-indicators hidden-sm hidden-xs"> <#list image.getSiblings() as cur_img> <li class="${(cur_img?counter == 1)?then('active', '')}" data-slide-to="${(cur_img?counter == 1)?then(0, (cur_img?counter - 1))}" data-target='carousel-<@portlet.namespace />'></li> </#list> </ol> <div class="carousel-inner" role="listbox"> <#list image.getSiblings() as cur_innerImage> <div class="${(cur_innerImage?counter == 1)?then('active', '')} item"> <div class="aspect-ratio aspect-ratio-custom aspect-ratio-middle"> <img alt="${cur_innerImage.getAttribute("alt")}" src="${cur_innerImage.getData()}"> </div> </div> </#list> </div> <a class="left carousel-control" href='#carousel-${request.get("portlet-namespace")}' role="button" data-slide="prev"> <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="right carousel-control" href='#carousel-${request.get("portlet-namespace")}' role="button" data-slide="next"> <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> </section> </#if>
5. 上傳圖片,添加web content
可以在Document and Media中新建個資料夾,然後上傳一些圖片
利用我們剛剛創建好的structure和template創建web content。在我這裡我的Aspect Ratio是26%,即長度大概是寬度的4倍。
也可以使用Liferay內置的圖片編輯器添加一些濾鏡效果。
6. 預覽並發佈
創建完成之後,就可以發佈了,然後可以使用Web Content Display portlet在頁面上顯示了。
你可以嘗試改變流覽器尺寸,試試外掛程式是否保持長寬比。
也可以使用Simulation工具來預覽我們設置的響應式尺寸是否正常(67%)。
這樣一個回應式的圖片滾動外掛程式就完成啦。
希望你能喜歡。