Search code examples
templatesoptimizationdust.js

Possible to optimize this Dust "logic"?


I'm working in a Dust partial and want to display a fixed header if a condition is met.

First, I want to know if the user said they're working in a given city. If they aren't in any cities in my list, I want to display nothing...UNLESS they live in Hawaii. Then I want to show that same header.

{@select key=workingCity}
  {@eq value=1}Fixed Header{/eq} {! Pittsburgh !}
  {@eq value=2}Fixed Header{/eq} {! Paris !}
  {@eq value=3}Fixed Header{/eq} {! Phoenix !}
  {@default}
    {@eq key=state value=50} {! Hawaii !}
      Fixed Header
    {/eq}
  {/default}
{/select}

Is there any way I can avoid placing 'Fixed Header' in four different locations?

I know I could just reference another partial with that specific title inside it...but then I need to put that partial reference in four locations anyway!

Is this as optimized as it gets?


Solution

  • If you're using a new enough version of dust and dust-helpers, you can use the new {@any} and {@none} helpers-- they're for exactly this use case.

    {@select key=workingCity}
      {@eq value=1/} {! Pittsburgh !}
      {@eq value=2/} {! Paris !}
      {@eq value=3/} {! Phoenix !}
      {@any}Fixed Header{/any}
      {@none}
        {@eq key=state value=50} {! Hawaii !}
          Fixed Header
        {/eq}
      {/none}
    {/select}
    

    That brings you down to two instances of the header, which may be good enough. Documentation for these helpers is at Dust Helpers.

    You can also bring even more logic out of your template into a context helper, which is something Dust is really good at. That way, the logic remains in Javascript, and the template is just for display.

    {#showFixedHeader}
      Fixed Header
    {:else}
      Optionally something else!
    {/showFixedHeader}
    

    And in your context:

    {
      "showFixedHeader": function(chunk, context) {
        var workingCity = context.get('workingCity');
        var state = context.get('state');
        return [1,2,3].indexOf(workingCity) > -1 || state === 50;
      }
    }
    

    Now your template is super readable, and if you add a fourth city the template doesn't have to change at all.