Home > Software design >  Go PDF template: can't evaluate field X in type struct
Go PDF template: can't evaluate field X in type struct

Time:03-29

My question might be looks similar from existing question but it's totally different. Please read it in details.

So, I'm trying to generate 2 different PDF based on specific condition. Let's say, if condition A then the PDF has stamp, else it's not.

I have 2 struct which is:

//no stamp
    templateData := struct {
        Name                string
    }{
        Data:               data,
        DataDetails:        dataDetailsPDF,
        Name:               name,
    }

//with stamp
    templateDataStamp := struct {
        Name                string
                StampLink:          string
    }{
        Data:               data,
        DataDetails:        dataDetailsPDF,
        Name:               name,
                StampLink:          config.PDF.StampImageLink,
    }

Based on those 2 struct, I have if condition like this:

pdfRequest := pdf.NewRequestPDF(config, "Body.html", "Header.html", "Footer.html")

    if data.Valid == "1" {
        err = pdfRequest.ParseTemplate(templateDataStamp)
        if err != nil {
            return nil, helper.Error(codes.Internal, tracestr, err)
        }
    } else {
        err = pdfRequest.ParseTemplate(templateData)
        if err != nil {
            return nil, helper.Error(codes.Internal, tracestr, err)
        }
    }

It works well till I'm trying to generate PDF without stamp (the else condition), it shows an error like this

can't evaluate field StampLink in type struct{
        Name                string
    }

Below is my html template that contains StampLink:

<img src="{{.StampLink}}" width="150px" alt="">

Is there any solution to fix the error if the {{.StampLink}} on html template is empty?

I'm sorry if it is too long, but I want to explain as much detail as possible, thank you.

CodePudding user response:

You are using same template therefore passing struct without StampLink causes error.

Use struct with all field and conditions to render it if not empty.

From docs

{{if pipeline}} T1 {{end}}
    If the value of the pipeline is empty, no output is generated; otherwise, T1 is     executed. The empty values are false, 0, any nil pointer or interface value, and any     array, slice, map, or string of length zero. Dot is unaffected.

{{ if .StampLink }} <img src="{{.StampLink}}" width="150px" alt=""> {{ end }}
  • Related