Condition Rendering

a:if

In an axml, a:if="{{condition}}” is used to tell whether a code block is to be rendered.

copy
<view a:if="{{condition}}"> True </view>

Besides, a:elif and a:else can be used to add an else branch.

copy
<view a:if="{{length > 5}}"> 1 </view>
<view a:elif="{{length > 2}}"> 2 </view>
<view a:else> 3 </view>

block a:if

Because a:if is a control attribute, and can only be used in one component. For conditional rendering of multiple components at once, an <block/> component can be used to contain those components, and add one a:if to control.

copy
<block a:if="{{true}}">
  <view> view1 </view>
  <view> view2 </view>
</block>

Note: <Block/> is not a component but just a packaging element. It does not render anything in the page but accepts control attribute only.

Compare a:if with hidden

  • The template in a:if may contain data binding. So, when the a:if condition value changes, the framework has a process of local rendering which is used to ensure destroy or re-render in case of the change. In addition, when the initial render condition is false, the a:if does not trigger any render action, and starts local rendering when the condition turns true for the first time.
  • The hidden controls show/hide, but the component is always rendered.

Generally, the a:if has a higher overhead when frequently toggled, while the hidden has a higher initial rendering overhead. As a result, hidden is better for frequent toggles. If the running conditions do not toggle much, a:if is preferred.