如何根据标题重写 URL? [英] How do I rewrite URL's based on title?

查看:52
本文介绍了如何根据标题重写 URL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个相当开放的问题,我只是在寻找最佳途径.

This is a fairly open-ended question, and I'm just looking for the best possible avenue.

用户可以发布带有标题的链接.我希望我的 URL 用于 SEO 目的来显示这些标题.与我认为 stackoverflow 的工作方式大致相同.

Users can post links with titles. And I want my URL's for SEO purposes to display those titles. Much in the same way I believe stackoverflow works.

所以如果标题是我的 foobar 刚和我的猫做的"

So if the title is "My foobar just made out with my cat"

我希望 URL 为:www.website.com/posts/My-foobar-just-made-out-with-my-cat

有什么想法吗?

非常感谢!

推荐答案

我在旧的 Rails 2.x 应用程序中使用了它.可能有更好的方法来擦洗标题...

I used this in an old Rails 2.x app. There may be a better approach to scrubbing the title...

(进入你的模型)

def to_param
  seo_uri
end

def seo_uri
  "#{self.id}-#{self.title.gsub(/[^a-z0-9]+/i, '-').gsub(/-{2}/, '-').gsub(/-$/, '')}"
end

希望这会有所帮助!

更新

对此答案的评论表明有一种新方法可供 Rails 3 用户使用:#parameterize.此方法的 Rails API 文档显示它应该如何使用(剪切-粘贴):

Comments on this answer indicated there is a new method available for Rails 3 users: #parameterize. The Rails API document for this method shows how it should be used (cut-n-paste):

class Person
  def to_param
    "#{id}-#{name.parameterize}"
  end
end

@person = Person.find(1)
# => #<Person id: 1, name: "Donald E. Knuth">

<%= link_to(@person.name, person_path %>
# => <a href="/person/1-donald-e-knuth">Donald E. Knuth</a>

这篇关于如何根据标题重写 URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆