2018年12月9日 星期日

[css/scss] 自適寬度的圖片(Responsive Image)-img隨div大小改變自行縮放


將同一張圖片不切割就能用不同的尺寸顯示,效果預覽如下:


這是利用照片當作背景,並以圖片的短邊為依據,不經剪裁就能以需要的比例呈現,利用css對背景圖片設定的支援功能,設定像是background-position,如果圖片過大時從哪個位置開始進行剪裁,以下為scss撰寫的原始碼。

首先,先準備一個Parent Class,『%』後面加上名稱,在編譯成css後不會看到這個class。
%responsive-image {
 display: flex;
 width: 100%;
 flex: 100%;
 background-size: cover;
 background-repeat: no-repeat;
 background-position: center center;
}

接著設定一個image-1x1的class,使所有的圖片都能以1比1的比例顯示。
// H:1, W:1
.image-1x1{
 @extend %responsive-image;
 padding-bottom: percentage(1 / 1);
}
以此類推,如果需要顯示一個長300、寬400的圖片,請在括號內填入『(3/4)』,就能達到想要的效果!

在html裡面套用這個class。
<div class="image-1x1" style="background-image: url('https://picsum.photos/400/?image=318');"></div>


我搭配bootstrap的grid system寫了一個完整的範例,可以在codepen上找到[連結],請參考:

See the Pen Responsive Image by chenuin (@chenuin) on CodePen.



[css/scss] 水平時間軸(Horizontal Timeline)範例及原始碼分享


水平時間軸


為了方便客製化,這次使用scss來寫,並把幾個重要的參數拉出來寫,其中比較重要的是$event-num,如果有4個項目的話,會用全部的長度均分,因此請依照自己實際使用去修改這個參數。

style.scss
@import url('https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css');

$line-color: #FA8072;  // 水平線的顏色
$point-color: #FF4500; // 圓點的顏色
$point-size: 16px;     // 圓點的大小(直徑) 
$half-point-size: $point-size/2;
$active-font-color: #FA8072;
$inactive-font-color: rgba(0, 0, 0, 0.5);
$event-num: 4;  // 圓點(項目)數量

#timeline {
  ol {
    position: relative;
    display: block;
    margin-top: 50px;
    margin-bottom: 100px;
    height: 1px;
    padding-inline-start: 0;
  }

  li {
    position: relative;
    display: inline-block;
    float: left;
    width: calc(100% /  #{$event-num});
    height: 1px;
    background: $line-color;
    color: $inactive-font-color;
    .diplome {
      text-align: center;
      margin-top: 20px;
    }
    .point {
      content: "";
      display: block;
      width: $point-size;
      height: $point-size;
      border-radius: 50%;
      border: 1px solid $point-color;
      background: #fff;
      position: absolute;
      top: -#{$half-point-size};
      left: calc(50% - #{$half-point-size});
    }
    .timestamp {
      font-size: 14px;
      text-align: center;
    }
    &.active>.point {
      border: $half-point-size solid $point-color;
    }
    &.active>.diplome,
    &.active>.timestamp {
      color: $active-font-color;
    }
  }
}

如果習慣看css的人,可以利用一些線上的轉換網站(如:sassmeister)轉換成css。

index.html
<div class="container">
  <div id="timeline">
    <ol>
      <li class="active">
        <span class="point"></span>
        <h6 class="diplome">My Birthday</h6>
        <p class="timestamp">2018/06/01</p>
      </li>
      <li class="active">
        <span class="point"></span>
        <h6 class="diplome">Father's Day</h6>
        <p class="timestamp">2018/08/08</p>
      </li>
      <li>
        <span class="point"></span>
        <h6 class="diplome">Helloween</h6>
        <p class="timestamp"></p>
      </li>
      <li>
        <span class="point"></span>
        <h6 class="diplome">Christmas</h6>
        <p class="timestamp"></p>
      </li>
    </ol>
  </div>
</div>


原始碼放在codepen上[連結],歡迎參考:

See the Pen Horizontal Timeline by chenuin (@chenuin) on CodePen.


2018年11月18日 星期日

[Github] 用Django專案示範如何使用Travis CI自動測試


開始之前請先到Travis CI[官網]用Github帳號登入
同步github上的專案,並啟動需要測試的專案(Repository)!

請在根目錄新建檔案.travis.yml
使用語言為python,並用3.5和3.6版本。
language: python
python:
  - "3.5"
  - "3.6"

env則是設定這個腳本中的參數,後面install則是安裝這個專案所需的套件。
env:
  - DJANGO_VERSION=2.1
  - DJANGO_VERSION=2.1.2
# command to install dependencies
install:
  - pip install -q Django==$DJANGO_VERSION
  - pip install -r requirements.txt

針對這個專案我寫了一段測試(連結),script就是執行裡面預先寫好的元件測試。
script: python manage.py test

上傳Github後,可以看到測試的結果,我們分別設定了2個版本的python、2個版本Django,所以會產生4個執行結果,就不需要一一下載各個版本來進行測試囉!

如果測試成功會顯示passing,若失敗會顯示failing,我在readme.md加上的標誌方便知道結果,新增方法請參考下面:


完整檔案如下(連結):
# .travis.yml
language: python
python:
  - "3.5"
  - "3.6"
env:
  - DJANGO_VERSION=2.1
  - DJANGO_VERSION=2.1.2
# command to install dependencies
install:
  - pip install -q Django==$DJANGO_VERSION
  - pip install -r requirements.txt
# command to run tests
script: python manage.py test

完整專案請到Github(連結)下載。

2018年11月16日 星期五

[Symfony] Ubuntu16+PHP7 安裝Synfony3.4


這次作業軟體是Ubuntu16.04,安裝的php是7.0。

首先請下載symfony指令,並移到指定資料夾方便全域使用。
sudo curl -LsS https://symfony.com/installer -o /usr/local/bin/symfony
sudo chmod a+x /usr/local/bin/symfony

接著馬上就能新增一個專案,my_project可以替換成想要的專案名稱。
# create a symfony project
symfony new my_project 3.4

我第一次建完專案出現訊息提示"simplexml_import_dom() must be available",請指令安裝php-xml排除這個問題。
如果想確定環境是否符合symfony的執行需求,可用下面指令:
php my_project/bin/symfony_requirements

如果看到這樣的畫面,基本上就沒問題,下面還另外有一些建議,可以選擇性安裝!


將Symfony專案啟動的方式
# run application
cd my_project
php bin/console server:run

打開網頁 http://localhost:8080可以看到預設Symfony的頁面,收工囉~


2018年11月13日 星期二

[Boostrap] 透過scss自訂個人風格的主題(Theme)


Bootstrap將常用的Navbar、Button等元件定義好css
可以讓前端的開發更加快速,是最多人使用的前端開發套件!

但有時boostrap的設定不合意要怎麼辦呢?
而且這麼多人使用bootstrap是不是有失個人風格呢?
這時你可以下載scss的版本來定義屬於自己的bootstrap模板喔!

請新建一個檔案加入bootstrap,第一種方法是把所有的元件都引用:
// Custom.scss
// Option A: Include all of Bootstrap

@import "node_modules/bootstrap/scss/bootstrap";

或者有時你只需要使用bootstrap部分的元件
// Custom.scss
// Option B: Include parts of Bootstrap

// Required
@import "node_modules/bootstrap/scss/functions";
@import "node_modules/bootstrap/scss/variables";
@import "node_modules/bootstrap/scss/mixins";

// Optional
@import "node_modules/bootstrap/scss/reboot";
@import "node_modules/bootstrap/scss/type";
@import "node_modules/bootstrap/scss/images";
@import "node_modules/bootstrap/scss/code";
@import "node_modules/bootstrap/scss/grid";
以上二選一即可,另外還提供了bootstrap-grid、bootstrap-reboot兩種常用的部分元件集,像bootstrap-grid就是針對網頁排版的所有bootstrap元件集,在RWD的網站時非常便利。

接著,進入正題!例如btn-primary、text-primary等都是藍色(#007bff),如果要自訂為粉紅色(#e83e8c),請將重新定義的顏色寫在引用bootstrap之前,檔案內容如下:
// Custom.scss
$primary: #e83e8c;

@import "node_modules/bootstrap/scss/bootstrap";
所有的primary就會變成你定義的粉紅色(#e83e8c),基本上所有的參數都能在_variables.scss找到原始的設定,只要加上你需要修改的參數,就可以輕鬆打造屬於你的bootstrap主題囉!

參考資料:
https://getbootstrap.com/docs/4.0/getting-started/theming/

2018年11月2日 星期五

[Javascript] 用Javascirpt截圖的小幫手 html2canvas


請先到html2canvas的官網下載套件
https://html2canvas.hertzen.com/

在想要擷取的畫面加上一個id方便來獲取這個元件,這邊設成capture。
<div id="capture"> ... </div>

這時候就可以擷取儲存成canvas,這邊是直接將這個畫面加到網頁的結尾。
html2canvas(document.querySelector("#capture")).then(canvas => {
    // do something
    document.body.appendChild(canvas)
});
querySelector這邊請記得針對你要擷取的元件設定!

完整的範例如下:
<html>
 <head>
<html>
 <head>
  <title>Screenshots with JavaScript</title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" >
 </head>

 <body>
  <div class="container">
   <div class="row">
    <div class="col my-5">
     <!-- The Screenshot Component -->
     <div class="target">
      <div class="card text-center">
       <div class="card-header">
        Featured
       </div>
       <div class="card-body">
        <h5 class="card-title">Special title treatment</h5>
        <p class="card-text">With supporting text below as a natural lead-in to additiona    l content.</p>
        <a href="#" class="btn btn-primary">Go somewhere</a>
       </div>
       <div class="card-footer text-muted">
        2 days ago
       </div>
      </div>
     </div>

     <!-- Display Area -->
     <div class="mt-5 result border border-success">
      <p class="text-center">Display Here!</p>
     </div>

     <!-- Download Link -->
     <a herf="#" class="download-link btn">Download</a>
    </div>
   </div>
  </div>
  <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
  <script type="text/javascript" src="./html2canvas.min.js"></script>
  <script>
  $(document).ready(function() {
   html2canvas(document.querySelector(".target")).then(canvas => {
     $(".result").append(canvas);
     $(".download-link").attr("href", canvas.toDataURL());
   });
  });
  </script>
 </body>

</html>

2018年10月30日 星期二

[Vue.js] 使用美化頁面的小幫手Bootstrap


Bootstrap是最常用的前端開發套件,以下介紹在Vue.js的專案內如何使用。

除了一般直接下載原始碼並在<head>加入,Bootstrap其實已經提供Vue.js使用的套件。
以下使用webpack產生的專案來說明,先創立一個新的專案,並依造下面步驟安裝。
# install related packages
npm install jquery
npm install ajv

# install boostrap-vue
npm i bootstrap-vue
創立專案的方式可參考『安裝 Vue.js』方法二。

請依照你的需求在頁面加入css檔,通常我會放在main.js,這樣所有的頁面都能使用。
# src/main.js
import 'bootstrap/dist/css/bootstrap.css'
import 'bootstrap-vue/dist/bootstrap-vue.css'
此時已經可以用平常的方法套用bootstrap。

不過這麼一來就跟下載原始碼沒什麼兩樣了,我們還沒發揮BootstrapVue plugin的好處,接著在main.js裡註冊bootstrap的元件。
# src/main.js
import Vue from 'vue'
import BootstrapVue from 'bootstrap-vue'

Vue.use(BootstrapVue);

這時侯如果要在頁面裡加入一個button,你只要這樣寫:
# src/App.vue
<template>
    <div id="app">
        <b-button variant="primary">I am a Button</b-button>
    </div>
</template>

...

比較一下原始的寫法,是不是方便多了呢!
# src/App.vue
<template>
    <div id="app">
        <button class="btn btn-primary">I am a Button</button>
    </div>
</template>

...

另外,你也可以根據需求只載入需要的元件(Component),例如只加入按鈕的元件。
import { Button } from 'bootstrap-vue/es/components';
Vue.use(Button);
或
import bButton from 'bootstrap-vue/es/components/button/button';
Vue.component('b-button', bButton);

更多資訊可參閱https://bootstrap-vue.js.org/。

2018年10月29日 星期一

[Django] 內建管理系統(Admin)使用技巧


Django內建的管理系統,就類似phpmyadmin一樣,可以用網頁的方式來管理資料庫,請先確定urls.py內已經加入這個路徑。
# project/urls.py
from django.contrib import admin
from django.urls import path

urlpatterns = [
    path('admin/', admin.site.urls),
]

請先執行migrate,建立一個後臺使用者的資料表,再新增一個使用者來登入後台介面。
# apply admin models
python manage.py migrate

# create a user to login as admin
python manage.py createsuperuser

打開瀏覽器'http://your-ip-address/admin'就可以看到管理介面的登入畫面,請輸入剛剛設定的帳號密碼。

首先,建立一個models紀錄產品(Product)的資訊:
# myapp.models.py
class Product(models.Model):
    name = models.CharField(max_length=128)
    price = models.DecimalField(max_digits = 11, decimal_places = 2)
    count = models.IntegerField()
    created = models.DateTimeField(auto_now_add=True)
請執行以下指令,讓這個models生效,makemigrations的目的是將models.py的內容轉成sql,若models.py有任何異動,可以透過migrations針對修改的部分進行更新。migrate則是執行sql,也就是實際建立新的table。
python manage.py makemigrations
python manage.py migrate

執行結果請參考

方法一、
最簡單的使用方式,就是在admin.py註冊這個models。
# myapp/admin.py
from django.contrib import admin
from .models import Product

admin.site.register(Product)

此時,管理介面會多一個你註冊資料表Product。另外,上面的User則是一開始新增的superuser儲存的資料表。

新增資料後,預設的畫面如下,括號內的數字是自動遞增的ID,必須點開才能知道其他資訊,不方便管理。

方法二、
同方法一在admin.py內註冊models,此外我們重新定義回傳值,不再顯示流水編號,舉例我們能回傳產品名稱(name)。
# myapp.models.py
class Product(models.Model):
    name = models.CharField(max_length=128)
    price = models.DecimalField(max_digits = 11, decimal_places = 2)
    count = models.IntegerField()
    created = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        # value to display
        return str(self.name)

效果如下:


方法三、
# myapp/admin.py
from django.contrib import admin
from .models import Product

class ProductAdmin(admin.ModelAdmin):
    # fields to display
    list_display = ('id', 'name', 'price', 'created')

admin.site.register(Product, ProductAdmin)

效果如下:


進階使用

[Django] 如何設定static files(css, javascript, images)


請確定設定檔內的參數,通常已經預設寫入。
# project/settings.py
INSTALLED_APPS = [
    ...
    'django.contrib.staticfiles',
]

STATIC_URL = '/static/'
接下來,分此兩種情形:

(1) 開發階段 (DEBUG=True)
首先,在開發階段時,因為static files經常性的修改,因此先讀取STATICFILES_DIRS的設定。
# project/settings.py
DEBUG = True

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
    # another directory ...
]


建立一個新的static資料夾,在裡面依照習慣將檔案分類放好,可以參考一下我的分類方式:

當在templates中要使用static資料夾內的資源,請記得加入tag。
# templates/index.html
{% load static %}
<img src="{% static 'images/example.png' %}" alt="My image" />


(2) 佈建正式環境 (DEBUG=False)
在正式環境時,請加入STATIC_ROOT的設定,請注意STATIC_ROOT與STATICFILES_DIRS的名稱不能重複!只要Debug設為False,一定要加入這個設定,否則網頁無法正常開啟。
# project/settings.py
DEBUG = False

STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles")

接著,請執行指令,將static裡面的資料輸出到新的資料夾staticfiles內。
python manage.py collectstatic
此時,觀察一下兩個資料夾差別,會發現staticfiles內除了我們自己新增的images,Django內建的admin或其他套件所需的資源,都會一並新增至此。但因為js和css兩個資料夾是空的,所以載入時會被忽略。



若之後static資料夾內有任何修改,必須重複執行collectstatic的指令來更新。


【重點整理】比較三個相似參數的差別
1. STATIC_URL:
設定static files的URL前綴,按照設定的前綴+路徑、檔名產生URL,以本文example.png為例,STATIC_URL='/static/',因此透過URL 'http://your-ip-address/static/images/example.png'檢視example.png這個檔案。

2. STATICFILES_DIRS:
開發階段,static files存放的位置,可以寫入多個路徑。

3. STATIC_ROOT:
正式環境中,透過collectstatic指令,將STATICFILES_DIRS設定目錄下檔案,收錄到STATIC_ROOT指定目錄。

2018年10月4日 星期四

[Django] 支援多國語言的網站

internationalization(國際化)被簡寫為i18n,因為字首i和字尾n的中間共有18個字母。

安裝相關軟體
sudo apt-get install gettext

修改settings.py,在MIDDLEWARE加上所需的套件,LANGUAGES列出支援哪些語言,LOCALE_PATHS則是將語言的翻譯包儲存的路徑。
# project/settings.py
MIDDLEWARE = [
    ...,

    'django.middleware.locale.LocaleMiddleware',
]


LANGUAGES = (
    ('zh-tw', '繁體中文'),
    ('en', 'English'),
)
LOCALE_PATHS = (
    os.path.join(BASE_DIR, 'locale'),
)

新增一個html的模板,記得加入i18n的tag,頁面內想翻譯的字詞標註起來。另外在url的設定裡,將所有頁面區分成多個語言,也就是原先的路徑http://your.ip.address/welcome,可由http://your.ip.address/en/welcome來檢視英文版網站,中文網站則是打開http://your.ip.address/zh-tw/welcome。
# templates/index.html
{% load i18n %}

{% trans '一起唱DoReMi' %}
設定url
# myapp/views.py
def index(request):
    return render(request, 'index.html', {})

# project/urls.py
from myapp import views
from django.conf.urls.i18n import i18n_patterns
urlpatterns = i18n_patterns(
    path('', views.index, name='index'),
)

標註好想翻譯的字詞或段落後,請透過下列指令產生翻譯文件。
python manage.py makemessages -l en
python manage.py makemessages -l zh_TW

此時在locale資料夾內,會找到產生的檔案,msgid是你標註的字詞,請在msgstr寫入翻譯。針對重複的id,在文件內只能設定一種翻譯。
# locale\en\LC_MESSAGES\django.po
msgid "一起唱DoReMi"
msgstr "singing DoReMi together"
# locale\zh_TW\LC_MESSAGES\django.po
msgid "一起唱DoReMi"
msgstr "一起唱DoReMi"

翻譯完成後,將翻譯包編譯出*.mo
python manage.py compilemessages -l en
python manage.py compilemessages -l zh_TW
可以參考一下完成編譯的檔案結構
locale/
├── en
│   └── LC_MESSAGES
│       ├── django.mo
│       └── django.po
└── zh_TW
    └── LC_MESSAGES
        ├── django.mo
        └── django.po

4 directories, 4 files

這時就可以開啟瀏覽器查看成果囉!
http://your.ip.address/en/
http://your.ip.address/zh-tw/