CSV -> HTML Using Javascript Tutorial

Master lists, tutorials, wishlists, member adoption rules & prefixes
Post Reply
User avatar
KingHarry
Moderator
Moderator
Posts: 172
Joined: Fri Dec 08, 2023 6:13 pm

CSV -> HTML Using Javascript Tutorial

Post by KingHarry »

This tutorial assumes you're familiar with HTML/CSS already. I'll do my best to explain the Javascript parts! Big thank you to @JT for all the help with the Javascript!

See King's Castle and view the crew pages to see the finished product.

Doing this is going to take a bit of setup, but I promise it will speed up updating your crew page once it's all done. It will also look complicated at first, but I promise it's easy to understand once you get the hang of it.

If you need help, feel free to DM me on discord!

Step 1; Set up your CSV

You do not need to have the exact same columns as me. The Javascript is fully customisable, so you can add or take columns to your liking. You can even tweak the code to be a hex archive or anything else if you want! You can make your CSV wherever you want. I've used Excel, but Google Sheets would work perfectly well too.

There are just a few important things to keep in mind:
  • If using Excel, I recommend having a .xlsx version where you can filter and drag down formulas for new entries, then save an additional .csv version that you overwrite whenever you do updates. If using Google Sheets, just export as .csv whenever you update.
  • Whatever order you want your petz to be in, you need to filter for it before saving the .csv. The Javascript will not reorder your petz.
  • If you want to split your crew pages by breed/hexed/etc, you will need to create a column for this so you can filter per page in the code. In my example, 'PhotoBreed' does this. You can name your column whatever you want. If you have lots of petz, this is highly recommended. The more petz on a page, the longer it takes to load!
  • If you want an image, you need to have the image pathway. In my opinion, the best way to do this is to name your images after the pet, and then set up a formula that you can drag down to automatically. The formula I use in my sheet is below. It works for Excel. It writes img/Photobreed/Name.png. You will need to adapt this to match your own image path.

    Code: Select all

    ="img/"&O2&"/"&A2&".png"
  • You can't use commas in your csv. As a work around, if I need a comma, I use a semicolon. The javascript will then change the semicolons into commas later on.
Image

Step 2; Export your CSV

Export your CSV and save it in the same location as your .html page.

Step 3; Add the Javascript to your page

You could save this in a separate script file, but personally I just add it directly to the page. This is because I have a page per breed and I didn't want to also have a script file per page per breed.

I have attempted to explain what the code is doing in the comments. I hope it makes sense!

Code: Select all

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>//pulls in csv
        $(document).ready(function() {
          $.ajax({
            type: "GET",
            url: "crew.csv",
            dataType: "text",
            success: function(data) {
              processData(data); 
            }
          });
        });
        
        //function to replace commas (use ; in csv)
        function replaceComma(str) {
          return str
          .replace(/;/g, ",");
        }
        
        //function to write table
        function processData(data) {
          // split header and info
          var dataLines = data.split(/\r?\n|\r/);
          var headers = dataLines[0].split(',');
        
          // make arrays
          for (var i = 1; i < dataLines.length; i++) {
              var petData = dataLines[i].split(',');
             if (petData.length == headers.length) {
        
          let row=""
          //turn into html strings
          let petShow = replaceComma(petData[1]);
          let petOther = replaceComma(petData[6]);
        
        
        //filter for breed,etc
        if (petData[14] == "Bulldog") {
          //writes code
          for (var j = 0; j < petData.length; j++) {
              //adds text
              row = "<tr><td><center><img src=\""
              //image
              + petData[15]
              + "\"></center></td>"
              //name
              + "<td><div style=\"font-size:1.2em;\"><b>"
              + petData[0]
              + "</b>"
              //loop for showname
                  if (petShow !== ""){
                  //showname
                  row += "<br><i>"
                  + petShow  
                  + "</i>"
                  }
              //gender
              row += "</div><div><b>Gender:</b> "
              + petData[2]
              //date 
              + "<br><b>Born:</b> "
              + petData[3]
              //creator
              + "<br><b>Bred by:</b> "
              + petData[5]
              //loop for title
                  if (petData[9] !== ""){
                  //titke
                  row += "<br><b>Title/s:</b> "
                  + petData[9]  
                  }
              //loop for other
                  if (petOther !== ""){
                  //showname
                  row += "<br><b>Other:</b> "
                  + petOther  
                  }
              //end
              row += "</div></td></tr>"
              ;
              
          }  } //write code
            document.getElementById("crew").innerHTML += row; //}
        }}}</script>
Remember to update line 6 of this code with your .csv's path!

Then in your page's body, add a table. If you change the table's ID from "crew", make sure you also update it in the second to last line of the javascript.

Code: Select all

<table id="crew"></table>
Step 4; Adjust the output

Image

This is where you adjust how your HTML will look! You are making the javascript write the HTML into the table.

PetData[x] refers to the columns in your CSV. Remember that the count starts at 0 - so in my CSV, pet name is 0, not 1.

If you don't want to filter your petz, remove the first two lines from the code in the screenshot, and one of the squiggly brackets in the last line in the screenshot.

If you are filtering your petz, change the column number to the one corresponding to your filter, and then change "Bulldog" to the value corresponding to what you're filtering for.

Changing the output HTML is going to be a bit tricky at first, but i promise it isn't confusing once you get the hang of it! Things to remember:
  • Wherever you see a PetData[x], change the number to the correct corresponding column in your CSV.
  • When adjusting the outputs, remember to check the HTML before and after, and remember that you're writing a table. You need to craft the javascript here so it'll write a table in HTML too.
  • Anything that's a loop will only write the HTML if the column in the CSV has data there. E.g. if there is no inputted showname, there will be no showname section.
Step 5; Save your HTML

Once you have finished adapting the javascript to suit your CSV, save your page! You should now see all your petz!

Image
Post Reply