Email Templates – How to Use Nested If Statements

emailemail-templates

I am trying to use nested if statements in my email template, like the following:

{{if subscriber.promo_group}}
    <p>You are one of the first {{var subscriber.promo_group}} subscribers.</p>
{{/if}}

{{if subscriber.coupon_code}}
    <p>Use code {{htmlescape var=$subscriber.coupon_code}} for {{htmlescape var=$subscriber.discount_amount}} off.</p>
    {{if subscriber.partner_coupon_code}}
        <p>Or, code {{var subscriber.partner_coupon_code}} for {{htmlescape var=$subscriber.partner_discount_amount}} off at checkout.</p>
    {{/if}}
{{else}}
    {{if subscriber.partner_coupon_code}}
        <p>Use code {{htmlescape var=$subscriber.partner_coupon_code}} for {{htmlescape var=$subscriber.partner_discount_amount}} off at checkout.</p>
    {{/if}}
{{/if}}

When I get my email, though, I get it like this:

You are one of the first 20 subscribers.

Use code XXXXX-QTEALK15 for $35 off.

Or, code XXXXX10OFF for 10% off at checkout.

{{else}}
Use code XXXXX10OFF for 10% off at checkout.

{{/if}}

Is it possible to use nested if statements in the Magento email templates?

Best Answer

If you look at the start of the Varien_Filter_Template class you will find the following two constants.

const CONSTRUCTION_DEPEND_PATTERN = '/{{depend\s*(.*?)}}(.*?){{\\/depend\s*}}/si';
const CONSTRUCTION_IF_PATTERN = '/{{if\s*(.*?)}}(.*?)({{else}}(.*?))?{{\\/if\s*}}/si';

In the regular expression of CONSTRUCTION_IF_PATTERN you will notice that it has the form of

{{if condition}} TEXT GOES HERE {{else}} OTHER TEXT GOES HERE {{/if}}

So, unfortunately nesting if statements is not possible as the first matched {{/if}} will be caught in the regular expression.

Although, the class offers something other than the {{if}} statements, the {{depend}} statement. It is almost the same as the {{if}} except it has no {{else}} functionality.

Luckily in your case, the nested conditions aren't complicated and can be done using {{depend}}. So you can have the following:

{{if subscriber.promo_group}}
    <p>You are one of the first {{var subscriber.promo_group}} subscribers.</p>
{{/if}}

{{if subscriber.coupon_code}}
    <p>Use code {{htmlescape var=$subscriber.coupon_code}} for {{htmlescape var=$subscriber.discount_amount}} off.</p>
    {{depend subscriber.partner_coupon_code}}
        <p>Or, code {{var subscriber.partner_coupon_code}} for {{htmlescape var=$subscriber.partner_discount_amount}} off at checkout.</p>
    {{/depend}}
{{else}}
    {{depend subscriber.partner_coupon_code}}
        <p>Use code {{htmlescape var=$subscriber.partner_coupon_code}} for {{htmlescape var=$subscriber.partner_discount_amount}} off at checkout.</p>
    {{/depend}}
{{/if}}

If it needs to be more complicated that this, it is best to just simplify your logic using a block class for the template.

Related Topic