How does Stack Overflow generate its SEO-friendly URLs?

后端 未结 21 2298
-上瘾入骨i
-上瘾入骨i 2020-11-22 04:27

What is a good complete regular expression or some other process that would take the title:

How do you change a title to be part of the URL like Stack

21条回答
  •  遇见更好的自我
    2020-11-22 04:51

    If you are using Rails edge, you can rely on Inflector.parametrize - here's the example from the documentation:

      class Person
        def to_param
          "#{id}-#{name.parameterize}"
        end
      end
    
      @person = Person.find(1)
      # => #
    
      <%= link_to(@person.name, person_path(@person)) %>
      # => Donald E. Knuth
    

    Also if you need to handle more exotic characters such as accents (éphémère) in previous version of Rails, you can use a mixture of PermalinkFu and DiacriticsFu:

    DiacriticsFu::escape("éphémère")
    => "ephemere"
    
    DiacriticsFu::escape("räksmörgås")
    => "raksmorgas"
    

提交回复
热议问题