在主题组件中重定向现有路由

要在主题组件中重定向现有的 Discourse 路由,您可以使用 api.modifyClass 来修改路由类。

更多信息请参阅 Ember 关于路由重定向的文档。示例如下:

<script type="text/discourse-plugin" version="0.8"> 
    // 修改标签路由。
    api.modifyClass('route:tag-show', {
        afterModel: function(tag, transition) {
            this._super(tag, transition);
            // 如果是星期日,重定向到 ID 为 20 的主题。
            if (today.getDay() == 6) {
                this.replaceWith("/t/20");
            }
        }
    });
</script>

如果您需要加载数据以决定重定向的位置或是否进行重定向,则必须让路由钩子返回一个 Promise,正如 Ember 关于异步路由的文档 中所讨论的那样。示例如下:

<script type="text/discourse-plugin" version="0.8">
    const ajax = require('discourse/lib/ajax').ajax;

    api.modifyClass('route:tag-show', {
        afterModel: function(tag, transition) {
            // 似乎顺序很重要,这行代码必须放在前面。
            this._super(tag, transition);

            // 重定向到第一个同时带有路由标签和 'canonical' 标签的开放主题。
            var path = `/tags/intersection/canonical/${tag.id}.json`;
            const context = this;
            return ajax(path).then(function(result){
                var topics = result.topic_list.topics.filter(function(topic) { 
                   return !topic.closed ;
                });
                if (topics && topics.length > 0) {
                    var topic = topics[0];
                    // 您需要考虑目标与源相同的情况。
                    // 您可以取消转换,但在此我们允许其继续而不进行重定向。
                    if (!transition.from || transition.from.parent.name != 'topic' || transition.from.parent.params.id != topic.id) {
                        context.replaceWith("/t/" + topic.id);
                    }
                }
            })
            // 捕获任何错误,以便(未重定向的)路由可以作为回退继续执行。
            .catch(function() {
                console.log('Error loading topics by ajax in tag show route afterModel hook.');
            });
        },
    });
</script>
8 个赞