Tutorial - Add dynamic content to a static web page generated with Cecil

View as Markdown

Find out how to add a call to an external API from your static web page

Objective

This tutorial describes how to use the Cecil site builder to display the contents of a dynamic page. All this while calling an API to retrieve and display information on a page generated via Cecil.

Find out how to add a call to an external API from your static web page.

Information regarding OVHcloud service administration and how to find appropriate assistance

When using OVHcloud guides, please be aware of the following conditions:

  • User instructions aim to provide as many details as possible but cannot cover individual use cases. You might need to adapt the pertinent actions to your requirements.
  • The OVHcloud ecosystem is built for flexibility and freedom of choice. Customers are therefore responsible for the secure and proper configuration of their services. To prevent data loss, we strongly recommend to apply backup strategies to all your important data.
  • Our guides and tutorials may reference third-party software or services in combination with OVHcloud solutions. The technical support provided by OVHcloud does not include the configuration of systems or products outside of our responsibility. This includes but is not limited to:
    • Operating systems and user interfaces (Windows, Debian, Plesk, etc.).
    • Any other third-party software (FTP clients, email software, etc.).
    • Services offered by other providers (DNS, APIs, user interfaces, etc.).

To receive the appropriate assistance for any issues you might experience, follow these guidelines:

  • You seek personalized advice or you would like to discuss a topic that is not covered in detail by our documentation?
    Join the OVHcloud Community to search for your topic and reach out to other users.
  • You need to report an incident regarding your OVHcloud service or you are experiencing difficulties in the OVHcloud Control Panel?
    Create a support request in our Help Centre.
  • You require professional assistance for your project or you need help with tasks outside our support scope?
    Visit our partner portal to search for experts who are familiar with OVHcloud solutions.
  • You are looking for more detailed information regarding our support levels and Professional Services?
    Please visit our web pages for OVHcloud support levels and OVHcloud Professional Services.

You can participate in improving our documentation:

  • You would like to share feedback to improve a guide page or you want to report insufficient information on a specific page?
    Use the "Was this page helpful?" buttons at the bottom of the page to let us know.
  • You would like to propose a specific documentation update?
    Use the "Edit this page" function, available at the bottom of the page and in the sidebar.

Requirements

  • Have an OVHcloud web hosting plan that includes SSH access. With this access, you can install one or more alternative solutions online, to those offered by default in our web hosting plans.
  • Be familiar with command line input.
  • You need to have installed and configured the Cecil application on your web hosting plan (see our tutorial on installing and configuring Cecil).

Instructions

The chosen example is to use one of the APIs of a service providing meteorological data. It relies on a city entered by the user.

The steps are as follows:

  • Create a new page on Cecil and add this page to the website menu.
  • Create an account and retrieve the key for making requests to the weather API.
  • Modify the .md file created by adding HTML code.
  • Add assets (JavaScript and CSS).
  • Build and test the solution.

Create a new page

Prepare your environment by logging in via SSH to your web hosting plan, and refer to the tutorial “Installation and configuration of Cecil” to install your Cecil application in a dedicated directory.

Create a directory and switch to it:

mkdir myWebSite
cd myWebSite

Using the OpenWeather API

For this tutorial, we will use an API provided by the OpenWeather website. It allows to retrieve weather information based on the name of a city.

Create an account on https://home.openweathermap.org/users/sign_up.
Once your account has been validated (by sending a confirmation email), go to the “My API keys” menu. A key was generated by default, retrieve it and save it for the rest of this tutorial.

Open Weather API key

Add HTML

Create a new page with the following command:

php cecil.phar new:page weather.md

Then edit the page that you generate:

nano pages/weather.md

Change the file header so that the page appears in the menu:

---
title: "Weather"
date: 2022-11-28
published: true
menu: hand
---

After the header, add the HTML code to display the chosen city, the temperatures returned by the API and a button to change the parameter:

---
title: "Weather"
date: 2022-11-28
published: true
menu: hand
---
<h1>Weather</h1>
<div>
    <span id="city">Roubaix</span>
    <div id="temperature"><span id="temperatureValue"></span> °C</div>
    <div id="modify">Change city</div>
</div>

Generate the HTML page with the following command:

php cecil.phar build

Check the result in your browser and click the "Weather" link that was added to the main menu:

Test new page

Add JavaScript

You cannot add a <script> tag to a Markdown file. You will need to modify the template provided by default.

Modify the template

Templates are arranged in the layouts directory. You can view them with the following command:

ls -la layouts

The file contains a blog directory and an index.html.twig file:

layouts directory

Open the file index.html.twig:

Cecil layouts index file

The file references a template that is not present in the directory. This file (and others) are actually inside cecil.phar. Files with the .phar extension are PHP file archives that can be manipulated without being decompressed. Unzip the files in this archive to make them visible:

php cecil.phar util:extract

Display the contents of the layouts directory again:

Cecil layouts directory including uncompressed files

Modify the default template to insert a <script> tag that will contain the code to call the API:

nano layouts/_default/page.html.twig

This tag and its contents must be placed before the closing tag </body> at the bottom of the page:

    </footer>
    {%- include 'partials/googleanalytics.js.twig' with {site} only ~%}
    {% block javascript %}
    <script src="{{ asset('script.js', {minify: true}) }}"></script>
    {% endblock %}
  </body>
</html>

When one or more asset files are modified, rebuild the cache with the following command:

php cecil.phar cache:clear:assets

If the modifications are not displayed in your web browser, clear the cache. You can also delete the files generated on your Web Hosting plan:

php cecil.phar clear

Then rebuild your solution using the command below:

php cecil.phar build

Add JavaScript

JavaScript files, such as CSS files, must be placed in the assets directory. You can organise them in different directories.

Create the previously mentioned script.js file at the root of the assets directory:

nano assets/script.js

Replace the value of the apiKey variable with the key retrieved earlier on the OpenWeather site.

let apiKey = '123456789'; // Replace this value
let city = 'Roubaix'; // Indicate here the default city that will be displayed on the weather page
getTemperature(city);  // Call function calling the API with the parameter "city"

// Add an event by clicking on the “Change city” button
let button = document.querySelector('#modify');
button.addEventListener('click', () => {
    city = prompt('Choose a city');
    getTemperature(city);
});

// API call function using an XMLHttpRequest object for asynchronous request
function getTemperature(city) {
    let url = 'https://api.openweathermap.org/data/2.5/weather?q=' + city + '&appid=' + apiKey + '&units=metric';
    let xhrQuery = new XMLHttpRequest();
    xhrQuery.open('GET', url);
    xhrQuery.responseType = 'json';
    xhrQuery.send();

    xhrQuery.onload = function() {
        if (xhrQuery.readyState === XMLHttpRequest.DONE) {
            if (xhrQuery.status === 200) {
                let city = xhrQuery.response.name;
                let temperature = xhrQuery.response.main.temp;
                document.querySelector('#city').textContent = city;
                document.querySelector('#temperatureValue').textContent = temperature;
            } else
                alert('A problem has occurred, please try later.');
            }
        }
    };
}

Tests

Now visit your website in a web browser:

Web page with JavaScript running

Click on “Change city” and enter the name of a municipality:

Select a new city Page updated

Conclusion

This tutorial shows you an example of how to integrate dynamic data retrieved from external sources using APIs. Build and maintain a website by manually editing the content of these pages, or create new ones. All this while enriching their content from other websites.

Go further

For specialised services (SEO, development, etc.), contact OVHcloud partners.

If you would like assistance using and configuring your OVHcloud solutions, please refer to our support offers.

Join our community of users.

Was this page helpful?