1

I am building a hexo blog theme in ejs, which will style my technical docs project. I want to allow the user to select a language (JavaScript or TypeScript). I would then like to type code snippets something like :

{% js %}
```JavaScript
var geolocation = require("nativescript-geolocation");
```
{% endjs %}

{% ts %}
```TypeScript
import geolocation = require("nativescript-geolocation");
```
{% endts %}

Then two button / a slider so the user could choose typescript or javascript (which would default to js). I am comfortable with the UI implementation, but am not sure how I would set a property to determine which of the above snippets is used?

and depending on which language the user had selected, the correct snippet would display. How could I implement this?

George Edwards
  • 8,979
  • 20
  • 78
  • 161

1 Answers1

1

Imagine that the output of your Hexo tags is something like this.

<div>
  <div class="codeblock js">
    var geolocation = require("nativescript-geolocation");
  </div>
  <div class="codeblock ts">
    import geolocation = require("nativescript-geolocation");
  </div>
</div>

Now, you have to write javascript to :

  • Display code blocks by default (default language)
  • Display code blocks in the desired language when a button is clicked
  • Save the selected language to display the right language when a page is refreshed or changed

Here is an example with jQuery library in a JSFiddle because session storage is not allowed in snippet on SO

In this example, I used .hide() and .show() method but you can also use CSS class to do this. Add a class (.addClass()) on desired language code blocks, and remove class (.removeClass()) on other code blocks with some css :

.codeblock {
  display:none;
}
.codeblock.active {
  display:block;
}
Louis Barranqueiro
  • 10,058
  • 6
  • 42
  • 52