HUGO

How to get query of urls.Parse

Hi,
I want to parse url youtube url to get the query video id in shortcode. Here is my code

{{ $link := .Get "link"}}
{{ $url := urls.Parse $link }}
{{ $q := $url.Query }}
{{ printf "%#v" $link }} 
{{ printf "%#v" $q.v }} 

<div class="videos-wrapper mx-auto">
       <div class="py-4">
          <iframe class="mx-auto" width="560" height="315" src="https://www.youtube.com/embed/{{$q.v}}" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
       </div>
</div>

Shortcode

{{<embed-youtube link="https://www.youtube.com/watch?v=UIExg0IVJ24&t=272s&ab_channel=Anphabe" >}}

The problem is the value of query ā€œvā€ was return [UIExg0IVJ24] in hugo. How can I get query value return only UIExg0IVJ24.
Thanks.

Use the .Get method to get the string value

{{ $link := .Get "link"}}
{{ $url := urls.Parse $link }}
{{ $q := $url.Query }}

++ {{ $videoId := $q.Get "v" }}

{{ printf "%#v" $link }} 
{{ printf "%#v" $q.v }} 

<div class="videos-wrapper mx-auto">
       <div class="py-4">
++          <iframe class="mx-auto" width="560" height="315" src="https://www.youtube.com/embed/{{$videoId}}" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
       </div>
</div>
4 Likes

Awsome, thanks @pamubay

It took me a minute to figure out what you were doing. Clever.
https://pkg.go.dev/net/url#Values.Get

2 Likes

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.