简体   繁体   中英

Jade - objects and mixins

So I am trying to pass an object to a mixin and I have my mixin as follows:

mixin summarySection(panelID, bodyID, title, options)
    div(class='panel panel-default panel-summary')
        div(id=panelID class='panel-heading' role='tab')
            h4(class='panel-title')= title
            div(class='pull-right')
                if(options.dropdown)
                    select
                        option #{options.dropdown.options}
                a(role='button' data-toggle='collapse' href='##{bodyID}' aria-expanded='#{options.expanded}' aria-controls=bodyID) +
        div(id=bodyID class='panel-collapse collapse' role='tabpanel' aria-labelledby=panelID class= options.hasOwnProperty('expanded') ? 'in' : '')
            div(class='panel-body')
                if block
                    block
                else
                    p Content goes here
            if (options.footer)
                div(class='panel-footer text-center')
                    a(href='#{options.footer.link}') #{options.footer.text}

I call the mixin as follows:

+summarySection('panelRecentActivity', 'bodyRecentActivity', 'Recent Activity', {'expanded': 'true', 'dropdown': {'options': 'Last 30 days'}})
+summarySection('panelStatements', 'bodyStatements', 'Statements')

It works fine when I call with all the variables but if I dont pass a certain variable in the object then it throws an error saying its undefined. For example for the second mixin call above I get the error Cannot read property 'dropdown' of undefined because its not defined.

How do I properly check if they are defined and avoid errors?

It is good practice to check if the values are available inside the function or mixin before using them. You can use conditional statement to avoid such problems. You can do following for example:

if options && options.footer
   a(href='#{options.footer.link}') #{options.footer.text}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM