Help:Scribunto/HTML Library usage notes


 * This page discusses a library used in the Lua programming language, through the Scribunto extension. If you are not using this extension, it will not apply to you.
 * ''This page simply contains some usage notes that simply expand on the full documentation.

Frequently, your modules will construct tables or other HTML structures that you will want to print. This is best done with the mw.html library. You can see documentation for this library here, but how return values are handled may cause some confusion.

Consider the following code, which is intentionally wrong:

This does NOT work. You might think that in the loop, you're adding additional rows below the header row, but it's the  element that's been assigned to , so the additional rows end up within the header cell.

Here's a comment-annotated version of the code above to demonstrate what's going on:

Using to fix the problem
The following code ensures that the  element is assigned to  :

Content-annotated version of the code that creates the table header:

Alternative approach
Note that the loop doesn't call, but the generated table is correct. That is because each iteration references the  variable, which is not reassigned and thus always refers to the   element.

This also means that the first part of the function could be written differently:

Which approach to take, using  or adding nodes one at a time, is a matter of preference, individual-wiki code-style conventions, and context. Do whichever version generates the easiest-to-understand code.

Storing references to sub-elements
Ok so we can use  to specify where we are within the table structure when we add new content. But what if we need to add new code in different places?

But now how can we add additional rows to ? As written, we can only add new things within the first  that we already tagged. The answer is to reference the table rows of the table as they are created, like this:

Now because  and later   are referencing a part of , we can tag it and actually we are continuing to append to  ! You can think of it as  being the parent object, and   (or whatever you choose to call the reference) being a location in.

Note: In the second ipairs loop,  typically I would just write   but I wrote out a much longer variable name here to reduce confusion with table rows / the variable. Also, the  just denotes that we never use the key part of the key-value pair, but if you wanted you could write   with no issue.