Skip to main content Link Search Menu Expand Document Toggle dark mode Copy Code (external link)

#with : Context Switching Helper

Change the data context to a specific object, simplifying property access within the block. Properties can be accessed directly without the object prefix.


On this page

Syntax

{{#with object}}
  <!-- Properties accessed directly -->
{{else}}
  <!-- Optional fallback if object is null -->
{{/with}}

With Alias:

{{#with object as | alias |}}
  <!-- Use alias to reference the object -->
{{/with}}

Parameters

Parameter Type Required Description
object Object Yes The object to set as the current context
alias Identifier No Optional variable name for the object

Special Variables

Variable Description
this / . Reference to the current context object
../ Access parent context

Examples

Basic Context Switching

{{#with model.user}}
  <h2>{{name}}</h2>
  <p>Email: {{email}}</p>
  <p>Age: {{age}}</p>
{{/with}}

Data:

doc.Params["model"] = new {
    user = new {
        name = "John Doe",
        email = "john@example.com",
        age = 30
    }
};

Output:

<h2>John Doe</h2>
<p>Email: john@example.com</p>
<p>Age: 30</p>

With Else Block

{{#with model.user}}
  <div class="user-profile">
    <h2>{{name}}</h2>
  </div>
{{else}}
  <div class="no-user">
    <p>No user profile available</p>
  </div>
{{/with}}

Accessing Parent Properties

<h1>Order #{{model.orderNumber}}</h1>

{{#with model.customer}}
  <div class="customer">
    <h2>Customer: {{name}}</h2>
    <p>Order Number: {{../orderNumber}}</p>
  </div>
{{/with}}

Using Alias Syntax

{{#with model.currentUser as | user |}}
  <div>
    <p>Logged in as: {{user.name}}</p>
    <p>Role: {{user.role}}</p>
  </div>
{{/with}}

Nested With Blocks

{{#with model.company}}
  <h1>{{name}}</h1>

  {{#with address}}
    <address>
      {{street}}<br>
      {{city}}, {{state}} {{zip}}<br>
      Company: {{../../name}}
    </address>
  {{/with}}
{{/with}}

Underlying Implementation

The {{#with}} helper compiles to the following Scryber template structure:

<template data-bind="{{object}}">
  <!-- Main content with direct property access -->
  <template data-visible="false">
    <!-- Optional else content if object is null -->
  </template>
</template>

For the alias syntax {{#with object as | alias |}}, it creates a variable binding that makes the object available under the specified name.


Notes

  • Empty/null objects trigger the {{else}} block
  • Use {{.}} to reference the entire context object
  • Use {{../property}} to go up one level
  • Use {{../../property}} to go up two levels
  • Alias names must be valid identifiers
  • Context switching simplifies deeply nested property access

See Also