George Edwards George Edwards - 7 months ago 36
Node.js Question

Selective ejs template based on user selected environment

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 %}
var geolocation = require("nativescript-geolocation");
{% endjs %}

{% ts %}
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?


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

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

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 {
} {