Site icon Coding is Love

Displaying code in Facebook instant articles 📱

I’m a fan of Facebook instant articles. They load very fast! 🎉 Click through rate and engagement is also very high for instant articles so I setup instant articles for ‘Coding is Love’

There’s a WordPress plugin which can be installed for basic setup, then the latest posts from the blog are imported and converted into instant articles.

Converted? Yup Instant articles have a different markup. Only a few HTML elements are supported. Okay, all good and articles are imported but there were few issues.

Only H1 and H2 are supported in Heading elements. Other elements like H3, H4 will be converted into H2 while displaying the article.

This is all fine but the code blocks were completely ignored and shown as plain text! Instant articles ignore code, pre elements and show them as plain text.

This is a coding blog and displaying code blocks is very important. I tried blockquote and few other elements supported by instant articles but nothing worked 😞

Finally, After reading the documentation clearly I was able to display code blocks clearly in this way.

There’s an element called Figure in which an Iframe can be embedded which can have any html elements so I placed a pre block inside the Iframe and styled it a bit and there’s our code block!

Here’s the final code block

<figure class="op-interactive">
<iframe>
<pre style="overflow:auto; background-color:#fafafa; border:1px solid #ebebeb;padding:10px;color:#020202;font-size:10px;">
Code block goes here
</pre>
</iframe>
</figure>

Here’s a sample code block

<figure class="op-interactive">
<iframe>
<pre style="overflow:auto; background-color:#fafafa; border:1px solid #ebebeb;padding:10px;color:#020202;font-size:10px;">
Public Sub getWeather()
Dim xmlhttp As New MSXML2.xmlhttp, myurl As String, xmlresponse As New DOMDocument
myurl = "http://api.openweathermap.org/data/2.5/weather?apikey=4a2360d14bf33378079d2e2d49e35ddb&amp;mode=xml&amp;units=imperial&amp;q=" &amp; Sheets(1).Range("A2").Value
xmlhttp.Open "GET", myurl, False
xmlhttp.Send
xmlresponse.LoadXML (xmlhttp.responseText)
Sheets(1).Range("B2").Value = xmlresponse.SelectNodes("//current/temperature/@value")(0).Text
'MsgBox (xmlresponse.getElementsByTagName("temperature")(0).Attributes(1).Text)  Alternate method to parse XML
End Sub
</pre>
</iframe>
</figure>

Removing op-interactive class from figure element will throw an error in the articles editor. Also, RemovingOverflow: auto style causes abnormal font size issues so use it too. Here’s how code looks in instant article.

Wrapping up

Read the official documentation, try styling it even better. If you did then drop a link in comments 🙂

Exit mobile version