মূল কনটেন্টে যান
🐹
emberjs learning
গাইড•6 · Template Optimization

Use {{#let}} to Avoid Recomputation

impact · MEDIUM30-50% reduction in duplicate workplan · দিন ০৪৪
আগে নিজে — এই কোডে কী ভুল, ঠিকটা কেমন হবে?

Incorrect (recomputes on every reference):

// app/components/user-card.gjs
<template>
  <div class="user-card">
    {{#if (and this.user.isActive (not this.user.isDeleted))}}
      <h3>{{this.user.fullName}}</h3>
      <p>Status: Active</p>
    {{/if}}

    {{#if (and this.user.isActive (not this.user.isDeleted))}}
      <button {{on "click" this.editUser}}>Edit</button>
    {{/if}}

    {{#if (and this.user.isActive (not this.user.isDeleted))}}
      <button {{on "click" this.deleteUser}}>Delete</button>
    {{/if}}
  </div>
</template>
পুরো rule · Correct আর ব্যাখ্যা — আগে নিজে লিখুন, তারপর খুলুন

Use {{#let}} to compute expensive values once and reuse them in the template instead of calling getters or helpers multiple times.

Incorrect (recomputes on every reference):

// app/components/user-card.gjs
<template>
  <div class="user-card">
    {{#if (and this.user.isActive (not this.user.isDeleted))}}
      <h3>{{this.user.fullName}}</h3>
      <p>Status: Active</p>
    {{/if}}

    {{#if (and this.user.isActive (not this.user.isDeleted))}}
      <button {{on "click" this.editUser}}>Edit</button>
    {{/if}}

    {{#if (and this.user.isActive (not this.user.isDeleted))}}
      <button {{on "click" this.deleteUser}}>Delete</button>
    {{/if}}
  </div>
</template>

Correct (compute once, reuse):

// app/components/user-card.gjs
<template>
  {{#let (and this.user.isActive (not this.user.isDeleted)) as |isEditable|}}
    <div class="user-card">
      {{#if isEditable}}
        <h3>{{this.user.fullName}}</h3>
        <p>Status: Active</p>
      {{/if}}

      {{#if isEditable}}
        <button {{on "click" this.editUser}}>Edit</button>
      {{/if}}

      {{#if isEditable}}
        <button {{on "click" this.deleteUser}}>Delete</button>
      {{/if}}
    </div>
  {{/let}}
</template>

Multiple values:

// app/components/checkout.gjs
<template>
  {{#let
    (this.calculateTotal this.items) (this.formatCurrency this.total) (this.hasDiscount this.user)
    as |total formattedTotal showDiscount|
  }}
    <div class="checkout">
      <p>Total: {{formattedTotal}}</p>

      {{#if showDiscount}}
        <p>Original: {{total}}</p>
        <p>Discount Applied!</p>
      {{/if}}
    </div>
  {{/let}}
</template>

{{#let}} computes values once and caches them for the block scope, reducing redundant calculations.