Category: Intermediate using of twig with the JCI-Plugin
Intermediate using of twig with the JCI-Plugin
Create JSON out of JSON: Use it for a liveticker with “Auto Refresh API Ajax”
Challenge: Display the data from https://waterservices.usgs.gov/nwis/iv/?format=json&sites=01407600¶meterCd=72279&siteStatus=active
Local JSON stored at http://api.json-content-importer.com/extra/json/waterservices.usgs.gov.json
Simply displaying data is easy – create a Plugin template with the above URL and this Twigcode (Shortcode: [jsoncontentimporterpro nameoftemplate=NAME_OF_TEMPLATE])
Location: {{value.timeSeries.0.sourceInfo.siteName}}<br> Date: {{value.timeSeries.0.values.0.value.0.dateTime | date("Y-m-d", "America/New_York") }} <br> Time: {{value.timeSeries.0.values.0.value.0.dateTime | date("H:i", "America/New_York") }}<br> Water Level: {{value.timeSeries.0.values.0.value.0.value}}
In Action:
Location: Shrewsbury River at Sea Bright NJDate: 2022-06-27
Time: 04:12
Water Level: -0.92
Display this data with the “Auto Refresh API Ajax” Plugin- Way 1:
- Install the Plugin
- Create a HTML-Div like
<div id="araatest">load data</div>
- Go to the “Auto Refresh AA” menu and insert this:
- URL: See above
- What: value.timeSeries.0.values.0.value.0.value
- Where:
div[id="araatest"]
Display this data with the “Auto Refresh API Ajax” Plugin- Way 2:
Create a new JSON-Feed with the JCI-PRO-Plugin by adding a new plugin-template:
- Name: waterservices-json
- URL: https://waterservices.usgs.gov/nwis/iv/?format=json&sites=01407600¶meterCd=72279&siteStatus=active
- twig-template:
{"time": "{{"now" | date("d.m.Y, H:i:s") }}", "data": "Location: {{value.timeSeries.0.sourceInfo.siteName}}, Date: {{value.timeSeries.0.values.0.value.0.dateTime | date("Y-m-d", "America/New_York") }}, Time: {{value.timeSeries.0.values.0.value.0.dateTime | date("H:i:s", "America/New_York") }}, Water Level: {{value.timeSeries.0.values.0.value.0.value}}"}
Shortcode:
[jsoncontentimporterpro nameoftemplate="waterservices-json"]
This page with this Shortcode should be something like this:
http://api.json-content-importer.com/json-waterservices-usgs-gov/
Adding “?show=oc” removes the template and gives pure JSON:
http://api.json-content-importer.com/json-waterservices-usgs-gov/?show=oc
This JSON we can use in “Auto Refresh API Ajax”:
- Install the Plugin
- Create a HTML-Div like
<div id="araatest">load data</div>
- Go to the “Auto Refresh AA” menu and insert this:
- URL: http://api.json-content-importer.com/json-waterservices-usgs-gov/?show=oc
- What: data
- Where:
div[id="araatest"]
PRO: Openweather Forecast – weather at a location
sunrise: 05:15:19
sunset: 21:17:54
temp: 23.61 Celcius, feels_like 23.65 Celsius
windspeed: 3
Deutscher Wetterdienst 02:00 - 00:00:
There is a high potential for the development of severe thunderstorms.
See how this is done:
- this page gets lat & lon as input, e. g. from /pro-openweather-forecast-serach-location-show-weather/
JCI-Template:
- urlparam4twig: lat#lon#su
- URL:
{% set lat = 48.1371079 %}{% if urlparam.lat %}{% set lat = (urlparam.lat | e) %}{% endif %} {% set lon =11.5753822 %}{% if urlparam.lon %}{% set lon = (urlparam.lon | e) %}{% endif %} https://api.openweathermap.org/data/2.5/onecall?lat={{lat}}&lon={{lon}}&appid=...
- twig-template:
current time at {{urlparam.su|e}}: {{ (current.dt+timezone_offset) | date("d.m.Y, H:i:s") }}, timezone: {{timezone}}<hr> sunrise: {{ (current.sunrise+timezone_offset) | date("H:i:s") }}<br> sunset: {{ (current.sunset+timezone_offset) | date("H:i:s") }}<br> temp: {{current.temp-273.15}} Celcius, feels_like {{current.feels_like-273.15}} Celsius<br> windspeed: {{current.wind_speed}}<br> {% if (alerts|length)>0 %} {{alerts.0.sender_name}} {{(a.start+timezone_offset)| date("H:i") }} - {{(alerts.0.end+timezone_offset) | date("H:i") }}: <br>{{alerts.0.description}} {% endif %}
PRO: API Zippopotamus, Shortcode-Parameter httpstatuscodemustbe200
The API http://zippopotam.us/ gives Citynames and Coorindates to a Zipcode. The JCI-PRO-Plugin can use that for a “Zipcode to City-Search”.
This done this way:
Examples: Houston, US, TX | Munich, DE, Germany
1 .JCI-Shortcode:
httpstatuscodemustbe200=no tells the plugin to accept also non-ok-API-answers
[jsoncontentimporterpro nameoftemplate="zip" httpstatuscodemustbe200=no]
2. JCI template:
- url:
http://api.zippopotam.us/{% if urlparam.co %}{{urlparam.co}}{% else %}US{% endif %}/{% if urlparam.zip %}{{urlparam.zip}}{% else %}80636{% endif %}
- urlparam4twig: zip#co
- twig-template:
{% if urlparam.co %}{% set coun = urlparam.co %}{% else %}{% set coun = "DE" %}{% endif %} <form action=/pro-api-zippopotamus-shortcode-parameter-httpstatuscodemustbe200/> <select name="co" id=jciinput> <option value="DE" {% if coun =="DE" %}selected{% endif %}>Germany</option> <option value="US" {% if coun =="US" %}selected{% endif %}>United States</option> </select> <input type=text name=zip placeholder="Insert Zipcode" value="{% if urlparam.zip %}{{urlparam.zip}}{% else %}80636{% endif %}"> <input type=submit id=jciinput value="Search Zipcode for City"> </form> <hr> {% if places %} <strong>Found:</strong><br> <ol>{% for p in places %}<li> <a href="https://www.google.com/maps/search/{{p.latitude}},{{p.longitude}}" target="_blank">{{ attribute(p, 'place name') }} ({{ attribute(p, 'state abbreviation') }})</a> </li>{% endfor %}</ol> {% else %} {% if urlparam.zip %} no City to this Zipcode {{urlparam.zip}} found {% endif %} {% endif %} <style> #jciinput { border-radius: 5px; width: 320px; height:35px; background: #eee; color: black; } </style> <hr> Examples: <a href="/pro-api-zippopotamus-shortcode-parameter-httpstatuscodemustbe200/?co=US&zip=77004">Houston, US, TX</a> | <a href="/pro-api-zippopotamus-shortcode-parameter-httpstatuscodemustbe200/?co=DE&zip=80636">Munich, DE, Germany</a>
PRO, twig: Replace \r\n in JSON to HTML-Linefeeds
Challenge:
Display JSON from http://api.json-content-importer.com/extra/json/novida.inschool.fi.json and replace the “\r\n” linefeeds by “<br>”
Solution:
Use the twig-command “replace”
In Action:
Koulutuspaikka:Lieto
Koulutuksen sisältö:
Isännöinnin ammattitutkinto uudistui. Tule päivittämään osaamistasi! Tai aloita opinnot, jotka johtavat isännöintialan tutkintoon.
Koulutus sopiikin hyvin sinulle, joka
• toimit isännöitsijänä, mutta alan tutkinto puuttuu tai haluat päivittää osaamistasi,
• olet alanvaihtaja ja olet kiinnostunut isännöitsijän tehtävistä tai
• toimit esimerkiksi kiinteistönvälittäjänä ja haluat laajentaa toimintaasi isännöintiin.
Tavoite
Oman tavoitteesi teemme yhdessä sinun kanssasi koulutuksen alussa. Laadimme kanssasi suunnitelman, jonka tavoite voi olla vaikkapa perehtyminen yhden tutkinnon osan aiheisiin tai koko tutkinnon suorittamisen. Olipa tavoitteesi pienempi tai suurempi, saat koulutuksen aikana hyvät edellytykset suorittaa koko tutkinto tai tutkinnon osa.
Sisältö
Isännöinnin ammattitutkinto koostuu yhdestä pakollisesta sekä kahdesta valinnaisesta tutkinnon osasta.
Pakollinen tutkinnon osa: Isännöinnin toimintaympäristön hallinta
Valinnaiset tutkinnon osat (ryhmä I, josta valitaan 1 kpl): Asunto-osakeyhtiön isännöinti tai Vuokratalon isännöinti
Valinnaiset tutkinnon osat (ryhmä II, josta valitaan 1 kpl): Asumisneuvonta, Tekniset palvelut isännöinnissä, Uudiskohteen isännöinti tai Isännöintityön kehittämissuunnitelman laatiminen.
Toteutus
Teemme kanssasi henkilökohtaisen koulutusohjelman. Sen aikana käyt yhdessä kouluttajasi kanssa läpi niitä aiheita, joihin tarvitset valmennusta. Valmennus kestää noin vuoden, jona aikana pidät kouluttajasi kanssa yhteisiä koulutustunteja, tutustut alan kirjallisuuteen, teet erilaisia alaan liittyviä tehtäviä jne. Tutkinnon suorittamista varten sinulla tulee olla joko alan työpaikka tai työharjoittelupaikka tai –paikkoja siten, että isännöintialan vuosikello täyttyy.Jatkuva haku
PRO: JSON & Slider – How to do it with the jQuery Lightslider-Lib
Your challenge:
You have some URLs to Images in your JSON-Feed. Those images should be displayed in a image-slider.
There are many ways to do that:
One way is to use a PRO-slider like Smartslider and feed him with RSS, build out of JSON.
Another way is to use the jQuery lightSlider Library (see also here).
- Example JSON: http://api.json-content-importer.com/extra/example-gen-cp-ts/example_events_venues.json
- Create a new JCI-Template:
- Name:
lightslider
- URL:
http://api.json-content-importer.com/extra/example-gen-cp-ts/example_events_venues.json
- twig-Template:
- Name:
<link type="text/css" rel="stylesheet" href="http://sachinchoolur.github.io/lightslider/src/css/lightslider.css"> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <script src="http://sachinchoolur.github.io/lightslider/src/js/lightslider.js"></script> <ul id="lightSlider"> {% for d in _context %} <li> <img src="{{d.venue.img}}"> </li> {% endfor %} </ul> <script type="text/javascript"> $(document).ready(function() { $("#lightSliderDemo").lightSlider({ speed: 1500, auto: true, loop: true }) }); </script>
ATTENTION: In this Twig-code are three Script-Tags, loading code from remote servers. You can do that for testing. For a productive website you should host the JS-libs on your own servers!
- “jquery.min.js” you can add via the JCI-options, Tab “Extra”
- “lightslider.css” / “lightslider.js” you find at http://sachinchoolur.github.io/lightslider/ at “Download”. In the zip you find a folder “dist”. Copy the files from that (js and css) to your server and insert the URL to the two libs in the JCI-template.
Insert this Shortcode on a WordPress-Page:
[jsoncontentimporterpro nameoftemplate=lightslider]
In Action:
PRO: Calc with data from 2 JSON-URLs by merging the JSON-feeds
Challenge:
You have two JSON feeds you want to merge and calc with the JSON-values.
Example-Solution:
Example JSON-Feeds:
http://api.json-content-importer.com/extra/json/n1.json
and
http://api.json-content-importer.com/extra/json/n2.json
Create a new JCI-Template, name it e. .g “2json” and use one JSON-feed-URL as “URL of Template”
http://api.json-content-importer.com/extra/json/n1.json
twig:
{% set secondjsonurl = "http://api.json-content-importer.com/extra/json/n2.json" %} {% set sc = "Fetching URL failed: A valid URL was not provided." %} {% set json2feed = (sc | doshortcode ) %} {% set json2feedk = (json2feed| json_decode ) %} no2 from the 1st JSON-feed: {{ no2 }}<br> this is the data from the 2nd JSON-feed: {{json2feedk | json_encode}} <br> now calc no1 * no2: {{ json2feedk.no1 * no2 }}
Shortcode:
[jsoncontentimporterpro name=2json orderofshortcodeeval=10]
Explanation:
- “sc” is a string containing a JCI-shortcode for retrieving the 2nd JSON-URL. This Shortcode could also one with just [jsoncontentimporterpro id=...] for using another JCI-Template (in case the request is more complex).
- The “sc”-shortcode gives back {{_context | json_encode}}: This means the whole JSON is returned as pure string. Hence json2feed=(sc|doshortcode) executes the shortcode and sets json2feed as a JSON-string
- json2feedk=(json2feed|json_decode) converts the JSON-string to an JSON-array, which can be used just like the root-JSON-array of the 1st JSON-feed: json2feedk.no1 * no2
Importaint settings:
- Add “orderofshortcodeeval=10” to the shortcode! Otherwise the Shortcode in the Source might be executed at the wrong place
In action:
no2 from the 1st JSON-feed: 5
this is the data from the 2nd JSON-feed: {"no1":"8","unused":5433,"urlparam":{"lat":"","lon":"","su":"","zip":"","co":""}}
now calc no1 * no2:
40
PRO: Display JSON as a Chart -amCharts-Plugin
This plugin shos you how to display JSON-data in a Chart. For that we use the amChart-Plugin.
In Action:
JSON: http://api.json-content-importer.com/extra/json/chart.php
twig-template:
<!-- Styles --> <style> #chartdiv { width: 100%; height: 500px; } </style> <!-- Resources --> <script src="https://www.amcharts.com/lib/4/core.js"><\/script> <script src="https://www.amcharts.com/lib/4/charts.js"><\/script> <script src="https://www.amcharts.com/lib/4/themes/animated.js"><\/script> <!-- Chart code --> <script> am4core.ready(function() { // Themes begin am4core.useTheme(am4themes_animated); // Themes end var chart = am4core.create("chartdiv", am4charts.XYChart); chart.hiddenState.properties.opacity = 0; // this creates initial fade-in chart.data = [ {% for c in _parent %} { country: "{{c.country}}", visits: {{c.visits}} } {% if (not loop.last) %},{% endif %} {% endfor %} ]; var categoryAxis = chart.xAxes.push(new am4charts.CategoryAxis()); categoryAxis.renderer.grid.template.location = 0; categoryAxis.dataFields.category = "country"; categoryAxis.renderer.minGridDistance = 40; categoryAxis.fontSize = 11; var valueAxis = chart.yAxes.push(new am4charts.ValueAxis()); valueAxis.min = 0; valueAxis.max = 24000; valueAxis.strictMinMax = true; valueAxis.renderer.minGridDistance = 30; // axis break var axisBreak = valueAxis.axisBreaks.create(); axisBreak.startValue = 2100; axisBreak.endValue = 22900; axisBreak.breakSize = 0.005; // make break expand on hover var hoverState = axisBreak.states.create("hover"); hoverState.properties.breakSize = 1; hoverState.properties.opacity = 0.1; hoverState.transitionDuration = 1500; axisBreak.defaultState.transitionDuration = 1000; /* // this is exactly the same, but with events axisBreak.events.on("over", function() { axisBreak.animate( [{ property: "breakSize", to: 1 }, { property: "opacity", to: 0.1 }], 1500, am4core.ease.sinOut ); }); axisBreak.events.on("out", function() { axisBreak.animate( [{ property: "breakSize", to: 0.005 }, { property: "opacity", to: 1 }], 1000, am4core.ease.quadOut ); });*/ var series = chart.series.push(new am4charts.ColumnSeries()); series.dataFields.categoryX = "country"; series.dataFields.valueY = "visits"; series.columns.template.tooltipText = "{valueY.value}"; series.columns.template.tooltipY = 0; series.columns.template.strokeOpacity = 0; // as by default columns of the same series are of the same color, we add adapter which takes colors from chart.colors color set series.columns.template.adapter.add("fill", function(fill, target) { return chart.colors.getIndex(target.dataItem.index); }); }); // end am4core.ready() <\/script> <!-- HTML --> <div id="chartdiv"></div>
PRO: xml/kml-Feed creating – API adsbexchange – Flight Tracking
The site https://www.adsbexchange.com/ offers tons of feeds with info about flights.
Example: https://samples.adsbexchange.com/traces/2021/08/01/22/trace_full_440122.json
Local stored JSON: http://api.json-content-importer.com/extra/json/adsbexchange-trace_full_394a0b.json
Out of such JSON-data with the flight route you can create other feeds, like a KML-Feed. See how this can be done:
Create a JCI-Template:
- URL: https://samples.adsbexchange.com/traces/2021/08/01/22/trace_full_440122.json
- Name: kmladsbexchange
- twig-template:
<?xml version="1.0" encoding="UTF-8"?> <kml xmlns="http://www.opengis.net/kml/2.2"> <Document> {% for k,v in trace %} <Placemark> <name> <![CDATA[ {{desc}}: {{r}} ]]></name> <description> <![CDATA[ Alt: {{v.8.alt_geom}} ]]></description> <Point> <coordinates>{{v.1}},{{v.2}}</coordinates> </Point> </Placemark> {% endfor %} </Document> </kml>
In Action: http://api.json-content-importer.com/kmladsbexchange/?show=oc