How to Handle Null Values in Golang Templates when Comparing with Slice Elements?

DDD
Release: 2024-10-25 12:35:03
Original
288 people have browsed it

How to Handle Null Values in Golang Templates when Comparing with Slice Elements?

Handling Null Values in Golang Templates

Scenario

In Golang's database/sql package, Null[Type] structs help handle database values and their possible null values. However, testing for null values can be challenging. Using .Value to print SQL fields is straightforward, but evaluating against values in more complex scenarios can lead to issues.

Issue

Consider the following template code:

<select name="y">
   {{ range .SomeSlice }}
       <option value="{{ . }}" {{ if eq $.MyStruct.MyField.Value .}}selected="selected"{{ end }}></option>
   {{ end }}
</select>
Copy after login

This code attempts to set the selected attribute based on the equality of $.MyStruct.MyField.Value and .. However, if .MyField is not Valid, an error occurs.

Solution

There are two solutions to this issue.

Using Nested if Statements

{{if $.MyStruct.MyField}}
    {{if eq $.MyStruct.MyField.Value .}}selected="selected"{{end}}
{{end}}
Copy after login

Using the with Directive

<select name="y">
   {{range $idx, $e := .SomeSlice}}
       <option value="{{.}}">{{with $.MyStruct.MyField}}
               {{if eq .Value $e}}selected="selected"{{end}}
           {{end}}</option>
   {{end}}
</select>
Copy after login

Note:

Null[Type] structs are non-nil, so check the Valid field to determine if Value() will return a non-nil value.

{{if $.MyStruct.MyField.Valid}}
    {{if eq $.MyStruct.MyField.Value .}}selected="selected"{{end}}
{{end}}
Copy after login

The above is the detailed content of How to Handle Null Values in Golang Templates when Comparing with Slice Elements?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template