I have the Google Calendar component set up to pull in the next upcoming Facebook event from a calendar feed. In the calendar’s description attribute, this gives me the full event page text with the URL at the end. Since the descriptions for events are sometimes quite long, I’d like to template a sensor that strips everything but the URL at the end from the description. I am not quite sure how to go about this though with templating, any help? There are often other URLs in the description, but the one I want is always the last line. ie:
{% set length = states.calendar.fb_events.attributes.description.split(" ") | length %}
{% set url = states.calendar.fb_events.attributes.description.split(" ")[length-1] %}
{{url}}
outputs:
ton.
https://www.facebook.com/events/XXXXXXX
So the line breaks are messing it up, that value is “ton.\n\nhttp://www.facebook.com/events/XXXX”. How can I split it by " " and linebreak? Using an additional split by “\n” isn’t doing it
Great! Glad it works for you. Yeah templates were a bit of a mystery for me too but once you get a few you start to get the hang of it. A lot is trial and error for me lol.
I’ll explain this one line by line so it helps to understand what we did.
The first line sets a variable that we called “length”. You can call it anything you want. It splits the attribute “description” of your calendar into an array every time it sees a space and tells us the number of variables in that array. We are looking for the last one so this is where we get that number.
The second line creates a new variable (we can again call it anything) and splits it by the space again but in the [] is the last variable in that array, because you mentioned the URL is always at the end.
The third line takes what we just got from the previous step and says let’s split it at “https” and just look for everything after that. This gets rid of the /n new line junk that we don’t want before “https”
The fourth line declares a new variable as “https”. We will need it since we thew it away in the third step.
Finally we join “https” back up with the rest of the url!