Jump to content

Extension:ArrayFunctions/Essentials/Separating concerns

From mediawiki.org

In the previous chapter we saw how to divide your code into reusable chunks and abstract away complex computations. In this chapter, we take that approach one step further, and use it to completely split the creation of an array from displaying an array.

Separating data from display

[edit]

In standard MediaWiki, raw data is often interwoven with how it gets displayed. For example, a page may depend on a number of templates to do some computation, and these templates are used on the page directly. For many pages, this is perfectly fine. However, when you have really data-heavy pages, it may either become difficult to maintain the many template calls, or it may become slow because computations are repeated often. Before Parsoid, the go-to approach to fix this was to use the Variables or the Arrays extension. Unfortunately, this is no longer the recommended approach as these extensions will not work with Parsoid.

With ArrayFunctions, you can separate the data processing from display by first creating an array holding all the data necessary to display the page. This approach makes your code easier to maintain, and reduces redundant computations, improving performance. The key idea is to first generate or retrieve all the necessary data and then display it using a separate template.

Example

[edit]

Suppose you have a list of products and their prices, and want to display the products on a page. Instead of interleaving the retrieval and display logic, you can use ArrayFunctions so separate these concerns.

1. Create the array: Use ArrayFunctions to define your array and perform the necessary computations. For example:

{{#af_list:
  {{#af_object: name=Laptop | price=1200 }}
| {{#af_object: name=Phone | price=800 }}
| {{#af_object: name=Tablet | price=450 }}
}}

2. Create the display: Create a template that displays the array. For example:

{{#af_foreach: {{{1}}} | | item | {{#af_get: {{{item}}} | name}}: ${{#af_get: {{{item}}} | price}}<br/> }}

3. Compose the template and the array:

{{Display products| {{#af_list:
  {{#af_object: name=Laptop | price=1200 }}
| {{#af_object: name=Phone | price=800 }}
| {{#af_object: name=Tablet | price=450 }}
}} }}