【问题标题】:Meteor: Select template conditionally based on url argument from controllerMeteor:根据控制器的 url 参数有条件地选择模板
【发布时间】:2015-11-25 00:26:57
【问题描述】:

你好,我有这条路线

#CoffeeScript
    Router.route 'tests/:slug/:type/question/add',
      name: 'addQuestion'
      controller: testsAddQuestionController

我有这个控制器

@testsAddQuestionController = testsQuestionsController.extend
  template: 'mcqQuestionForm'
  data: ->
    questions: TestQuestions.find()  
    test: Tests.findOne slug: this.params.slug

我想根据 :type 参数的值从控制器中选择模板,我尝试了两种方法:

@testsAddQuestionController = testsQuestionsController.extend
  template: if this.params.type is 'mcq' then 'mcqQuestionForm' else 'somethingelse'
  data: ->
    questions: TestQuestions.find()  
    test: Tests.findOne slug: this.params.slug

但是用这种方法我得到了错误this.params is undefined

第二种方法

 @testsAddQuestionController = testsQuestionsController.extend
      template: if Router.current().route.params.type is 'mcq' then 'mcqQuestionForm' else 'somethingelse'
      data: ->
        questions: TestQuestions.find()  
        test: Tests.findOne slug: this.params.slug

但是这种方法导致应用程序崩溃,有没有人知道如何访问路由参数以使这个条件成为从控制器中选择模板的条件?

【问题讨论】:

  • 您是否尝试过将模板定义为返回模板名称的函数
  • 您好,谢谢!我忘记将模板定义为函数,下面是我的答案,再次感谢!

标签: meteor controller iron-router


【解决方案1】:

这是我们的控制器的样子:

@testsAddQuestionController = testsQuestionsController.extend
  template: ->
    qType = Router.current().params.type
    if qType == 'practical'
      'practicalQuestionForm'
    else if qType == 'mcq'
      'mcqQuestionForm'
  data: ->
    questions: TestQuestions.find()  
    test: Tests.findOne slug: this.params.slug

出于某种原因(不知道为什么),如果我将当前路由器参数保存到一个变量中,然后将该变量用于 if 语句,那么它就可以工作。

希望对你有所帮助。

【讨论】:

    猜你喜欢
    • 2018-04-21
    • 1970-01-01
    • 1970-01-01
    • 2017-09-27
    • 1970-01-01
    • 2017-09-11
    • 2012-12-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多