Skip to content

How to display HTML code snippets in your elixir code without it rendering #42

Open
@Cleop

Description

@Cleop

HTML entities can be used to help you display code snippets without them rendering as the code they represent. For example:

Is actually written in the code as:

<code>
  &lt;%= component &quot;primary_button&quot;, value: &quot;I'm a Primary Button&quot; %&gt;
</code>

Where &lt; represents the less than or < symbol etc.

Rather than encoding your hard code and pasting it in statically, how can I dynamically encode my regular code into HTML entities so that I don't have to keep on updating/changing it as my code changes? I want to create a function that will read the contents of a file and then encode its contents so that this will update whenever the file is updated.

Encoding your code
At first I considered regex or some other form of replacement function however this would be complicated to cover all possibilities. So instead I came across the hex package:

https://hex.pm/packages/html_entities

To install the hex package add {:html_entities, "~> 0.3"} under deps to your mix.exs file and run mix deps.get.

Reading the contents of a file
Now that I can encode my code, I now need to be able to grab the code from within a given file in order to encode it. To do this I can use the File module like this:

File.read!("./web/templates/component/primary_button_example.html.eex")

This only works with the trailing bang ! otherwise it errors. This is because we want it to return the code to us, without the ! it will return a tuple instead.

So this function is now called where I want the code snippets to appear in the html file like this:

The function contains:

And on the browser we see:

Despite the availability of the hex package, it turns out that using File.read! I don't even need it.

😀

Relates to mindwaveventures/good-thinking-phoenix#115

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions