Function fetch_shortcode_js

Source
pub fn fetch_shortcode_js(
    url: &str,
    method: Option<&str>,
    json_body: Option<&str>,
    alt: Option<&str>,
) -> String
Expand description

Generates a JavaScript snippet that asynchronously fetches data from a URL using either the GET or POST HTTP method and injects the response into the DOM. The function also provides fallback content for crawlers/robots that do not support JavaScript. If the response has JavaScript code like , it will be executable.

§Parameters

  • url: A string slice containing the URL to which the HTTP request will be made.
  • method: An optional HTTP method, either GET or POST. Defaults to GET if None is provided.
  • json_body: An optional JSON string for the request body when using the POST method. Defaults to an empty JSON object ({}) if None is provided. Ignored if the method is GET.
  • alt: An optional alternative content to display in a <noscript> block for crawlers/robots without JavaScript. This is only used if the method is GET. Defaults to None.

§Returns

A String containing the generated JavaScript code that can be inserted into an HTML page. The script:

  • Sends an asynchronous fetch request to the specified URL.
  • If the response is successful, it injects the response content into the DOM.
  • If the request fails, it logs an error message to the browser’s console.
  • If an invalid HTTP method is passed (anything other than GET or POST), an HTML <output> element with an error message is returned instead of the JavaScript code.

If the GET method is used and alt is provided, the function also includes a <noscript> fallback to display a link in case JavaScript is disabled or not supported.

§Example

use tera_shortcodes::fetch_shortcode_js;
 
let js_code = fetch_shortcode_js(
    "https://example.com/data", 
    Some("POST"), 
    Some("{\"key\": \"value\"}"), 
    Some("No JavaScript fallback")
);

println!("{}", js_code);

This will generate JavaScript code to make a POST request to https://example.com/data with the provided JSON body, and include a fallback for users without JavaScript.

§Error Handling

  • If an unsupported HTTP method is provided (anything other than GET or POST), the function will return an HTML <output> element with an error message specifying the invalid method.