User:BryanDavis/Sandbox/Codesample

From Wikitech
Jump to navigation Jump to search

Template:Codesample is a template, so per mw:Help:Templates#Order_of_evaluation each argument is expanded before being passed on to the template itself. This is ok most of the time, but some code will legitimately include content that we do not want to pass through the wikitext parser.

Wikitext examples

An obvious example is example wikitext.

{{Codesample|name=wikitext|lang=moin|code={{Alert|This is an alert!}}}}
wikitext
<div class="alert alert-info"></div>

As with a pre tag, this can be worked around by wrapping the sample in <nowiki></nowiki>.

{{Codesample|name=wikitext|lang=moin|code=<nowiki>{{Alert|This is an alert!}}}}</nowiki>
wikitext
{{Alert|This is an alert!}}

Jinja examples

A more problematic example is Jinja or Mustache templates.

{{Codesample|name=html+jinja|lang=html+jinja|code=<p><a href="{{ url_for('logout') }}">logout</a></p>}}
html+jinja
<p><a href="[[:Template:Url for('logout')]]">logout</a></p>

Let's try the <nowiki></nowiki> hack...

{{Codesample|name=html+jinja|lang=html+jinja|code=<nowiki><p><a href="{{ url_for('logout') }}">logout</a></p>}}
</nowiki>
html+jinja
&lt;p&gt;&lt;a href="{{ url_for('logout') }}"&gt;logout&lt;/a&gt;&lt;/p&gt;

<nowiki></nowiki> sort of makes this one worse. Template expansion was blocked, which is what we wanted, but also all of the < and > characters were replaced with HTML entities and then treated as literals by <syntaxhightlight>.

One workaround is to use Template:(( and Template:)) to do the escaping manually.

{{Codesample|name=html+jinja|lang=html+jinja|code=<p><a href="{{((}} url_for('logout') {{))}}">logout</a></p>}}
html+jinja
<p><a href="{{ url_for('logout') }}">logout</a></p>

I'm wondering is there is a more magical hack for this though. Maybe something like a helper template that expands the HTML entities back to their character representations?

{{Codesample|name=html+jinja|lang=html+jinja|code={{Codesample/ExpandEntities|<nowiki><p><a href="{{ url_for('logout') }}">logout</a></p>}}}}
</nowiki>