mardi 19 avril 2016

How can I generate HTML code "on the fly" using a list of predefined strings?

I am trying to make a website which allows me to define a list of events and then it displays them in simple HTML, sorted into past (ascending order) and future (descending order).

The event list will be a list of tuples, the first element being a code for the date "YYYYMMDD", and the second being an html string, like so:

event_list = [
    (20160320, "<b>20th March '16</b> - Event 1<br><br>"),
    (20160506, "<b>6th May '16</b> - Event 2<br><br>"),
    (20150130, "<b>30th January '15</b> - Event 3<br><br>"),
    (20160815, "<b>15th August '16</b> - Event 4<br><br>")
];

Then it will generate the date code for today, using some kind of script like this:

now = new Date();
var today_code = now.getYear() + now.getMonth() + now.getDate();
today_code = parseInt(today_code);

giving a code of 20160420 for today, for example

and then there will be a section in the code that goes like this (please forgive my pseudocode, i dont know javascript or much HTML):

<h1>FUTURE:</h1>
sort(event_list, event.date_code, ascending); //sort events by date (smallest first)
for event in event_list:
    if event.date_code >= today_code:
        insert(event.html_text);

<h1>PAST:</h1>
sort(event_list, event.date_code, descending); //sort events by date (largest first)    
for event in event_list:
    if event.date_code < today_code:
        insert(event.html_text);

HOPEFULLY, this will generate a web page that looks like this:

FUTURE:

6th May '16 - Event 2

15th August '16 - Event 4

PAST:

20th March '16 - Event 1

30th January '15 - Event 3

I know it is very inefficient running through the list twice, but we aren't talking about 1000s of elements here, it think it should be fine. Sorting twice was the only way I could think of swapping the order of placement, I guess maybe iterating through the list in reverse could work too, if that is possible.

EDIT:
My question, reduced is, how can I (a) define a list like this, (b) sort this list, (c) iterate through the list and insert the relevant strings of HTML code.
I could do it in other languages, I just don't really know anything about HTML (beyond basic typesetting) or javascript, so I don't know what functions to use or the syntax




Aucun commentaire:

Enregistrer un commentaire