Search code examples
meteorcontrolleriron-router

Meteor: Select template conditionally based on url argument from controller


Hi I have this route

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

And I have this controller

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

And I want to select template from controller depending the value of :type parammeter, I tried two ways:

@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

But with this approach I get the error this.params is undefined

Second approach

 @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

But the applciation crashes with this approach, does any body know how to access to route parameters in order to make this conditionals for select template from controller?


Solution

  • Here is how our controller looks like:

    @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
    

    For some reason (no idea why) if I save the current Router param into a variable and then use the variable for the if statement then it works.

    Hope this helps you.