TUTORIAL - Create a Crypto Coin Comparison Bot - BASIC - Part 2

in #utopian-io7 years ago (edited)

wallpaper.png

What Will I Learn?

Welcome to the second part of how to create cryptocurrency coin comparison automatic posting bot for steemit ! In todays episode I want to show you guys following things:

  • Quick Introduction in mustache.js and example
  • Creating Template Files
  • Using mustache.js to fill these template files with example data
  • Saving resulting template as output.html

Requirements

Difficulty

  • Basic

Tutorial Contents

Quick Introduction in mustache.js and example

A funny coincidence happened and I posted yesterday a tutorial about mustache.js (Which was of course not intended!). You guys can find it here and I would recommend it, since it is showing the basics for mustache.js.

Anyway if you don't have the time to read through it, here is a short introduction with basic examples!

Mustache is a logic-less template syntax. It can be used for HTML, config files, source code - anything.
It works by expanding tags in a template using values provided in a hash or object.
(Source)

To use Mustache.js you have two options: A) Use strings B) Use templates

A) Use strings

With mustache.js it is possible to modify / render simple template strings. To do so one need to use the function Mustache.render(template, data). Whereas template can be a string or a html template.

var data = {
  name: "Moonrise",
  sayHello: function () {
    return 'Hello World';
  }
};

var output = Mustache.render("{{name}} says: {{sayHello}}", data);
console.log(output);

Will output Moonrise says: Hello World. It is possible to provide functions and / or simple values in the data object.

B) Use templates

Using templates is kinda the same as using strings, the only different is that you need to load the template via (e.g) jQuery->get its html content(which is a string)->and render it

<script id="template" type="x-tmpl-mustache">
            {{name}} says: {{sayHello}} !
</script>
   var data = {
        name: "Moonrise",
        sayHello: function() {
            return 'Hello World';
        }
    }
    
    var template = $('#template').html();
    var output = Mustache.render(template, data);

Will return the same as above.

Install Mustache.js

To use mustache.js later please run npm install mustache --save inside your console!

Creating Template Files

But how does mustache.js work in our case ? First of all we need to create template files, which provide the basic layout we later want. The idea behind to fill later the templates just with data and save the rendered templates as a new HTML file.

I won't go into detail how our templates should exactly look like since we are creating the rendering logic right now. The only idea is that we need one template file. It is our main template which includes the basic page layout (header, footer, body and a table). Inside the table we want for each individual coin a single row, which provides the basic layout for a row (coin-name, price, etc...).

In summary we create a file inside our templates folder: main.html. It should look similar to this:

main.html
<div id="header">Crypto Coin Compare</div>
<hr>
<div id="body">
    <table>
        <th>Name</th>
        <th>Price</th>

        {{#coin_rows}}
            <tr>
                <td>{{name}}</td>
                <td>{{price}}</td>
            </tr>
        {{/coin_rows}}
    </table>
</div>
<hr>
<div id="footer">Auto Generated :O</div>

main.html uses mustache.js syntax! {{coin_rows}} will be replaced with each rendered row for each coin we want to present. (I refer here to Non-Empty-Lists on mustache.js). Basically {{coin_rows}} will be replaced with a list of items where each item gets rendered with the content inside {{coin_rows}}. You will see below how it works !

Using mustache.js to fill these template files with example data

Let's come to the interesting stuff, how does one use mustache.js with nodejs ? In my examples above we always used jQuery... which is not available on nodejs. The solution is the filesystem! That's why we created a seperated HTML file for our template.

In NodeJS we have access to our local filesystem, meaning we can access and read main.html content. So lets come right into it and edit our index.js as follows:

var fs = require('fs');
var Mustache = require('Mustache');

const coins = [
    {
        name: 'Bitcoin',
        price: '10000 $'
    }, {
        name: 'Ethereum',
        price: '900 $'
    }
];

fs.readFile('templates/main.html', 'utf8', function (err, content) {
  if (err) throw err;

  const data = {
      coin_rows: coins
  };
  const renderedMain = Mustache.render(content, data);


  console.log(renderedMain);
});

Run it and this will be the output:
Screen Shot 2018-02-16 at 14.05.18.png

Let's break it down:

First we include Mustache and the Filesystem Library in our index.js, then we set the example data we want to present.

fs.readFile('templates/main.html', 'utf8', function (err, content) {...}

Reads the file main.html and returns it content utf8-encoded. Then we use Non-Empty-Lists to render our rows inside the template via mustache.js

const data = {
      coin_rows: coins
  };
const renderedMain = Mustache.render(content, data);

The output is pretty impressing, since we can add as many coins as we want and each coin gets it own rendered row!

Saving resulting template as output.html

Now that we have rendered our template with example data we want to save it to our local filesystem. For that create inside your out folder, a file named out.html and edit your index.js:

var fs = require('fs');
var Mustache = require('Mustache');

const coins = [
    {
        name: 'Bitcoin',
        price: '10000 $'
    }, {
        name: 'Ethereum',
        price: '900 $'
    }
];

fs.readFile('templates/main.html', 'utf8', function (err, content) {
  if (err) throw err;

  const data = {
      coin_rows: coins
  };
  const renderedMain = Mustache.render(content, data);

  writeToDisk(renderedMain);
});

function writeToDisk(content) {
    fs.writeFile('out/out.html', content, function (err) {
      if (err) throw err;

      console.log('Done saving output!');
    });
}

After rendering is done we call a new created function called writeToDisk(data) to write the rendered template inside out.html. To do so we use fs.writeFile('out/out.html', content, function (err) {...}, which takes output_file_path, content, callback as parameter.

Run node index.js and you should see the content of out.html changed! Feel free to add new coins in the array and rerun the script. It will always generate a new content inside out.html !

Screen Shot 2018-02-16 at 14.17.07.png

I hope you guys liked and understand it ! Next up is designing + using request.js to get the latest coin data!

GitHub

Curriculum



Posted on Utopian.io - Rewarding Open Source Contributors

Sort:  

Great post,thanks for shareing this post,please keep wirting..!

Your contribution cannot be approved because it does not follow the Utopian Rules.

  • If you create a GitHub repository with additional material (like code samples), make sure to choose the repository of the project your tutorial is about and not your own repository. You can provide links to your repository in your post.

Suggestions:

  • Even if you provide good quality posts, the expected format in tutorials category is that posts should teach about open source projects, and I'm not sure there is a proper project you can show directly you teach about it. I think that development category would be better for your contributions. Please re-read the rules and consider expected format in the categories.

You can contact us on Discord.
[utopian-moderator]

Hello @roj,
I See your point that there is no proper project to post my tutorial to. This is because I take and teach different aspects of different projects and ideas. This is the reason why I selected my own, since its fit the most. I teach about the creation off my project with explaning the technologies used.

In my opinion it fits more in the tutorial section than in the Development section. Developments are finished versions, Mine is just a prototype.
I accept your decision but I would ask you to recheck it, please :)

PS: Creating an own project and teach about its creation is also a tutorial about a Open Source project ;)

I will Stick to my decision that it fits more as tutorial and will Post Future Post under the Same section.

Thanks

I actually meant that your contribution will be more proper for development category when it's finished, of course not now. But I took advice from my supervisor about your post, and he agrees with me that tutorials with their own repositories could not be approved. That's why I suggested a change in your post format. I hope you could make it since I really like your tutorials and their detailed explanations. I would love to help you if you have questions about the proper format for the category.

@roj
Alright, that's my fault. I thought it would be okay to do tutorials about my own repositories. But anyway, I thought about another concept and would love to hear your opinion if it fits more the rules.

The idea is that I select (e.g for this tutorial series) everytime a different repository. For example in this tutorial I teached mainly about mustache.js and how to combine it with local template files. So I could have chosen mustache.js as repository.
The next part will be about request.js and how to use it / integrate it in my project. So I will select request.js as repository my tutorial will be about.

Is this something that could work ? And if so is it possible to change the repository for this part, so it is acceptable ? :)

Coin Marketplace

STEEM 0.15
TRX 0.15
JST 0.028
BTC 53699.14
ETH 2213.00
USDT 1.00
SBD 2.28