In Hugo templates, how do you check length of JSON file array? - hugo

In Hugo, you can assign the contents of a JSON file to a template variable:
{{ $json := getJSON "posts.json" }}
How do you check the length in a condition block?

You can use the eq function to compare the length:
{{ if (eq ($json | len) 0) }}
no data
{{ else }}
show posts
{{ end }}

You can use the len function to get the length:
{{$len := len $json}}

Related

How to return the attribute value from an array in Ruby?

I have a function which returns me a Array Objects, and I want to return the ID in an array (as I can have many objects), of which each object has one. Here's what I have tried.
iban_obj.map{ |id| id },
iban_obj.select(&:id)
Here is my iban_obj:
[{"url"=>"xxxx.json",
"id"=>360081391060,
"title"=>"Test Macro",
"active"=>true,
"updated_at"=>"2021-11-22T13:15:06Z",
"created_at"=>"2021-11-19T16:52:00Z",
"position"=>10002,
"description"=>"{{ iban }} {{ phone_number }} {{ email }}",
"actions"=>
[{"field"=>"comment_value_html",
"value"=>
"restriction"=>nil}]
Desired Result:
id_array = [360081391060]
id_array = iban_obj.map { |obj| obj['id'] }
When you call #map each whole object will be passed in. From there you have to just select the proper key like you would from any hash.
You can use dig method too..
banking_customer.map{ |customer| customer.dig('id') }

how to delete embed yagpdb custom command

(yagpdb custom command) i need to delete this embed 3 seconds after that it send, but {{deleteResponse 3}} doesn't work
{{ $id := reFind \d` .Cmd | toInt64 }}
{{ with (dbGet $id "afk") }}
{{ $user := userArg .UserID }}
{{ $eta := "" }}
{{ if gt .ExpiresAt.Unix 0 }} {{ $eta = humanizeDurationSeconds (.ExpiresAt.Sub currentTime) | printf "*%s will be back in around %s.*" $user.Username }} {{ end }}
{{ sendMessage nil (cembed
"author" (sdict "name" (printf "%s está AFK" $user.String) "icon_url" ($user.AvatarURL "256"))
"description" (joinStr "\n\n" $eta .Value)
"color" (randInt 0 16777216)
"footer" (sdict "text" "AFK desde")
"timestamp" .UpdatedAt
) }}
for me it worked to put the embed in a variable and then send the message storing the message id in another variable. After sleep for the seconds I wanted to show the embed, I deleted the message via ID and the embeded part was included.
Your code would look like this:
{{ $id := reFind \d` .Cmd | toInt64 }}
{{ with (dbGet $id "afk") }}
{{ $user := userArg .UserID }}
{{ $eta := "" }}
{{ if gt .ExpiresAt.Unix 0 }} {{ $eta = humanizeDurationSeconds (.ExpiresAt.Sub currentTime) | printf "*%s will be back in around %s.*" $user.Username }} {{ end }}
{{ $embed := cembed
"author" (sdict "name" (printf "%s está AFK" $user.String) "icon_url" ($user.AvatarURL "256"))
"description" (joinStr "\n\n" $eta .Value)
"color" (randInt 0 16777216)
"footer" (sdict "text" "AFK desde")
"timestamp" .UpdatedAt
}}
{{ $x := sendMessageRetID nil $embed }}
{{ sleep (3) }}
{{ deleteMessage nil $x }}
To delete yagpdb's response after a certain time, you have to store the response & the id of the response in a variable. Here's the code for doing it.
{{ $x := sendMessageRetID nil $embed }}
{{deleteMessage nil $x 3}}
In the above code, the bot sends the embed storing the embed's id in the variable "x" & then deletes the message stored in the variable"x" after 3 seconds. I hope it helped you.

How to pass multiple values from template to template?

My City struct is like this:
type City struct {
ID int
Name string
Regions []Region
}
And Region struct is:
type Region struct {
ID int
Name string
Shops []Destination
Masters []Master
EducationCenters []Destination
}
In main I try to do this:
tpl.ExecuteTemplate(resWriter,"cities.gohtml",CityWithSomeData)
Is it possible to do something like this inside template?
{{range .}}
{{$city:=.Name}}
{{range .Regions}}
{{$region:=.Name}}
{{template "data" .Shops $city $region}}
{{end}}
{{end}}
Quoting from the doc of text/template, the syntax of the {{template}} action:
{{template "name"}}
The template with the specified name is executed with nil data.
{{template "name" pipeline}}
The template with the specified name is executed with dot set
to the value of the pipeline.
This means you may pass one optional data to the template execution, not more. If you want to pass multiple values, you have to wrap them into some single value you pass. For details, see How to pass multiple data to Go template?
So we should wrap those data into a struct or a map. But we can't write Go code in a template. What we may do is register a function to which we pass these data, and the function may do the "packing" and return a single value which now we can pass to the {{template}} action.
Here's an example wrapper which simply packs these into a map:
func Wrap(shops []Destination, cityName, regionName string) map[string]interface{} {
return map[string]interface{}{
"Shops": shops,
"CityName": cityName,
"RegionName": regionName,
}
}
Custom functions can be registered using the Template.Funcs() method, and don't forget you have to do this before you parse the template text.
Here's a modified template which calls this Wrap() function to produce a single value:
const src = `
{{define "data"}}
City: {{.CityName}}, Region: {{.RegionName}}, Shops: {{.Shops}}
{{end}}
{{- range . -}}
{{$city:=.Name}}
{{- range .Regions -}}
{{$region:=.Name}}
{{- template "data" (Wrap .Shops $city $region) -}}
{{end}}
{{- end}}`
And here's a runnable example showing these in action:
t := template.Must(template.New("cities.gohtml").Funcs(template.FuncMap{
"Wrap": Wrap,
}).Parse(src))
CityWithSomeData := []City{
{
Name: "CityA",
Regions: []Region{
{Name: "CA-RA", Shops: []Destination{{"CA-RA-SA"}, {"CA-RA-SB"}}},
{Name: "CA-RB", Shops: []Destination{{"CA-RB-SA"}, {"CA-RB-SB"}}},
},
},
{
Name: "CityB",
Regions: []Region{
{Name: "CB-RA", Shops: []Destination{{"CB-RA-SA"}, {"CB-RA-SB"}}},
{Name: "CB-RB", Shops: []Destination{{"CB-RB-SA"}, {"CB-RB-SB"}}},
},
},
}
if err := t.ExecuteTemplate(os.Stdout, "cities.gohtml", CityWithSomeData); err != nil {
panic(err)
}
Output (try it on the Go Playground):
City: CityA, Region: CA-RA, Shops: [{CA-RA-SA} {CA-RA-SB}]
City: CityA, Region: CA-RB, Shops: [{CA-RB-SA} {CA-RB-SB}]
City: CityB, Region: CB-RA, Shops: [{CB-RA-SA} {CB-RA-SB}]
City: CityB, Region: CB-RB, Shops: [{CB-RB-SA} {CB-RB-SB}]
I guess CityWithSomeData is a slice, if so have a try like that:
type viewModel struct {
List []City
}
then, in your template:
{{range .List}}
{{$city:=.Name}}
{{range .Regions}}
{{$region:=.Name}}
{{template "data" .Shops $city $region}}
{{end}}
{{end}}
You need the generic dict function that allows to build a map[string]interface{} from a list of parameters.
See https://stackoverflow.com/a/18276968/328115

orderBy in ngRepeat using another variable property

Is it possible to sort items from one array based on another variable by only using orderBy and not adding a count property to the items in the array?
Lets say i have an array and a map in the controller:
$scope.x = [{no:1,name:"a"},
{no:2,name:"b"},
{no:3,name:"c"}];
$scope.y = { 1: [1],
2: [1,2,3],
3: [1,2] };
and the html will look like this:
<div ng-repeat="i in x | orderBy: y[i.no].length">
{{i.no}}
{{ y[i.no] }}
{{ y[i.no].length }}
</div>
output:
1 [1] 1
2 [1,2,3] 3
3 [1,2] 2
but it should be:
1 [1] 1
3 [1,2] 2
2 [1,2,3] 3
You could use a predicate function, to specify your condition.
Try this:
<div ng-repeat="i in x | orderBy: findOrder">
{{i.no}}
{{ y[i.no] }}
{{ y[i.no].length }}
</div>
And:
$scope.findOrder = function(elem){
console.log(elem.no);
return $scope.y[elem.no].length;
}
A working fiddle.

How to handle filter in Angular expression

Please have a look at below code
Json object
namelist = [{name: "Mayur" , checked : true }, { name: "Rayum" , checked : false }]
In HTML i want to show number of items which are checked true , for above Json object count should be 1.
{{namelist.length}} // gives me total count
//can we do something like below
{{ namelist.length | filter {checked:true} }}
which we give me only count of the filtered count.
Try this:
{{ (namelist | filter: { checked: true }).length }}
Try this: {{ (namelist | filter:{checked:true}).length }}
You can read about filters here

Resources