如下有一段代码
class Topic def to_param "#{id} #{name}".parameterize end end
此时如果该 topic 名字是i am iron man 那么路由便是: /id-i-am-iron-man
i am iron man
/id-i-am-iron-man
但如果 topic 名字是中文的话: 我是钢铁侠 那么路由会是: /id
我是钢铁侠
/id
那么如何更好的呈现「中文 url」呢?
Thus, only alphanumerics, the special characters "$-_.+!*'(),", and reserved characters used for their reserved purposes may be used unencoded within a URL.
http://stackoverflow.com/questions/1856785/characters-allowed-in-a-url
如果一定要展示“中文”需要转码成这样:
"#{id} #{URI.escape name}".parameterize # => id-%E4%B8%AD%E6%96%87
#1 楼 @Rei 看来是要抛弃友好显示「中文」的念头了
wikipedia 的中文 URL: http://zh.wikipedia.org/wiki/%E6%9D%BE%E6%9C%AC%E8%A1%8C%E5%BC%98
#1 楼 @Rei
如果是 "#{id} #{URI.escape name}".parameterize 的话
"#{id} #{URI.escape name}".parameterize
此时 url 不是这种形式么? http://localhost:3000/topic/68-e6-a8-a1-e5-9d-97-e5-8c-96-e6-99-ba-e8-83-bd-e6-89-8b-e8-a1-a83
http://localhost:3000/topic/68-e6-a8-a1-e5-9d-97-e5-8c-96-e6-99-ba-e8-83-bd-e6-89-8b-e8-a1-a83
#4 楼 @linjunzhugg 奥,我没实际跑过,那用
"#{id}-#{URI.escape name}"
好了。
可以考虑把汉字转换成拼音。
#5 楼 @Rei
这样子的话是 http://localhost:3000/topic/68%20%25E6%25A8%25A1%25E5%259D%2597%25E5%258C%2596%25E6%2599%25BA%25E8%2583%25BD%25E6%2589%258B%25E8%25A1%25A83
http://localhost:3000/topic/68%20%25E6%25A8%25A1%25E5%259D%2597%25E5%258C%2596%25E6%2599%25BA%25E8%2583%25BD%25E6%2589%258B%25E8%25A1%25A83
之前没做任何编码转换,直接就上了 #{id} #{name} 不过这样子当遇到 name 有空白字符时便进不了 route 直接 404 了
#{id} #{name}
#6 楼 @debugger 个人感觉如果用拼音的话,URL 看起来挺长挺乱的
#7 楼 @linjunzhugg 横杠手动加上。
#9 楼 @Rei 对哦,写个正则把特殊字符全部替换成 _
先用正则判断出是中文,就用拼音插件,转成拼音就好了