slug = 蛞蝓, slugify = 蛞蝓化, slugification ….
所以是什麼意思呢…看完這影片應該會不會更一頭霧水?!
網站或網誌的一般文章標題可能就是 This is apple,為了 SEO 方便現在網站都會將頁面標題放在網址上提高被搜尋的可能,所以網址就會變這樣:
http://orange.com/article/this%20is%20apple
不是很好看,所以就需要把網址變成蛞蝓…
http://orange.com/article/this-is-apple
然後 django 的 model 有支援一種型態讓你直接可以將標題存成這種格式。而且因為要在網址上顯示,所以最好也能符合大多瀏覽器對網址的要求。
class Article():
title = models.CharField(max_length=100)
content = models.TextField(max_length=1000)
slug = models.SlugField(max_length=40)
他在 django 是這樣被實做的。
def slugify(value):
"""
Normalizes string, converts to lowercase, removes non-alpha characters,
and converts spaces to hyphens.
"""
value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore')
value = unicode(re.sub('[^\w\s-]', '', value).strip().lower())
return mark_safe(re.sub('[-\s]+', '-', value))
php 的版本~~勒~~
/**
* Modifies a string to remove al non ASCII characters and spaces.
*/
static public function slugify($text)
{
// replace non letter or digits by -
$text = preg_replace('~[^\\pL\d]+~u', '-', $text);
// trim
$text = trim($text, '-');
// transliterate
if (function_exists('iconv')) {
$text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
}
// lowercase
$text = strtolower($text);
// remove unwanted characters
$text = preg_replace('~[^-\w]+~', '', $text);
if (empty($text)) {
return 'n-a';
}
return $text;
}
JavaScript
function slugify(str) {
return str.toLowerCase().replace(/ /g, "-")
.replace(/[^\w-]+/g, "");
}
參考資源
– slugify make a string usable
– in-django-what-is-a-slug
– string-slugification-in-python
– django slugify
– php slugify