【问题标题】:iron-router: replace special characters铁路由器:替换特殊字符
【发布时间】:2013-11-30 18:21:36
【问题描述】:

为了获得易于理解的共享链接,我不想只将._id 放在网址中,而是将.name 也放在网址中。

Router.map(function () {
    this.route('here', {
        path: 'here/:_id/:name/',
        template: 'here'
    })
}) 

问题在于.name 条目可以包含特殊字符,例如/

www.example.com/here/1234/name_with special-characters like / (<-this slash) /

有没有办法替换 Iron-router 中的斜杠(和其他特殊字符)?
(如果有很好的方法来处理这个问题,也许在某些情况下我什至不需要 id。)

如果我想使用&lt;a href="{{pathFor 'showCourse'}}"&gt;
我不能使用通配符path: 'here/:_id/*

谢谢

【问题讨论】:

  • 为什么允许在名称中使用斜杠作为url 的一部分?你这样做有什么特别的原因吗?

标签: meteor meteorite iron-router


【解决方案1】:

它并非特定于 Iron Router,但 JavaScript 的原生全局函数 encodeURIComponentdecodeURIComponent 就是为了这个目的而存在的:

encodeURIComponent("foo/bar");   // returns "foo%2Fbar"
decodeURIComponent("foo%2Fbar"); // returns "foo/bar"

我在我的项目中所做的是添加一个名为 slug 的字段并编写一个函数,从文档的标题生成一个 URL 友好的 slug 并且检查集合以确保 slug 是唯一的(否则它会酌情附加“-2”或“-3”等)。使用每个文档唯一的 slug 或类似字段,您可以将其用作唯一的查询参数并放弃 _id

【讨论】:

    【解决方案2】:

    扩展 Geoffrey Booth 的答案,您可以使用模板助手来完成此操作。

    定义一个模板助手来编码您的name 值(我将其设为全局,以便所有模板都可以重用它):

    Template.registerHelper('encodeName', function() {
      this.name = encodeURIComponent(this.name);
      return this;
    });
    

    然后,在您的模板中,您可以将此函数传递给 Iron-router 的 pathFor 助手:

    <a href="{{pathFor 'showCourse' encodeName}}">
    

    这适用于 Meteor 1.1.0.2。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-28
      • 1970-01-01
      • 1970-01-01
      • 2014-11-03
      • 2013-03-08
      • 2012-11-16
      相关资源
      最近更新 更多