【问题标题】:How do I create a URL slug extension?如何创建 URL slug 扩展?
【发布时间】:2019-12-09 10:32:44
【问题描述】:

我正在使用SpringKotlin 创建一个博客应用程序。对于每篇文章,我需要以编程方式生成一个 slug。例如,如果文章标题是“吉娃娃如何过马路”,则 slug 应该是“吉娃娃狗如何过马路”。

对于上下文,我的实体文件(截断)看起来像:

@Entity
class Article(
    var title: String,
    var slug: String = I_WANT_THIS_TO_BE_A_SLUG_FROM_THE_TITLE)

如何使用 Kotlin 扩展来实现这一点?

【问题讨论】:

    标签: spring spring-boot spring-mvc kotlin spring-data-jpa


    【解决方案1】:

    在您的Extensions.kt 文件中,添加以下代码:

    fun String.toSlug() = toLowerCase()
            .replace("\n", " ")
            .replace("[^a-z\\d\\s]".toRegex(), " ")
            .split(" ")
            .joinToString("-")
            .replace("-+".toRegex(), "-")
    

    然后在你的实体文件中使用扩展名:

    @Entity
    class Article(
        var title: String,
        var slug: String = title.toSlug())
    

    此外,如果您不希望 slug 可变,请将其添加为计算属性:

    @Entity
    class Article(
            var title: String) {
        val slug get() = title.toSlug()
    }
    

    参考文献

    我从Building web applications with Spring Boot and Kotlin(由Sébastien Deleuze 编写)了解了slug 扩展。有关完整上下文,请参阅Extensions.kt lines 28 - 33

    另外,感谢Dave Leeds 推荐了计算属性选项。查看他的 Kotlin 博客 Dave Leeds on Kotlin,了解深入的概念和指南。

    【讨论】:

      【解决方案2】:

      所有解释的另一种方式

      import java.text.Normalizer
      
      fun String.slugify(): String = Normalizer
                      .normalize(this, Normalizer.Form.NFD)
                      .replace("[^\\w\\s-]".toRegex(), "") // Remove all non-word, non-space or non-dash characters
                      .replace('-', ' ') // Replace dashes with spaces
                      .trim() // Trim leading/trailing whitespace (including what used to be leading/trailing dashes)
                      .replace("\\s+".toRegex(), "-") // Replace whitespace (including newlines and repetitions) with single dashes
                      .toLowerCase() // Lowercase the final results
      
      

      我创建了一个要点https://gist.github.com/raychenon/8fac7e5fb41364694f00e6ce8b8c32a8

      【讨论】:

        猜你喜欢
        • 2014-11-06
        • 2016-06-12
        • 1970-01-01
        • 2019-08-01
        • 2013-04-21
        • 2011-12-19
        • 1970-01-01
        • 1970-01-01
        • 2020-05-24
        相关资源
        最近更新 更多