How to display HTML code snippets in your elixir code without it rendering
- Dominant language
- Elixir
- Stars
- 1.7k
- Forks
- 112
- PR merge metrics
- No merged PRs in 30d
Description
[HTML entities](https://www.w3schools.com/html/html_entities.asp) 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:
```
<%= component "primary_button", value: "I'm a Primary Button" %>
```
Where `<` 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 https://github.com/LDMW/app/issues/115
Contributor guide
No contributing guide indexed for this repository
Assessment
This issue has not been assessed yet.