获取切片的头部或除头部以外的所有内容

时间:2019-05-16 09:13:24

标签: go go-templates

如何在Go模板中获取切片的头或尾? 我想用什么:

export class CheckboxComponent implements DoCheck, ControlValueAccessor {

...

    writeValue(value: boolean): void {
        this._isChecked = !!value;
        this._autoSelected = !!value;

        const control = this._controlDir.control;
        // Adding Validators.requiredTrue if Validators.required is set on control in order to make it work with template-driven required directive
        if (this.hasRequiredValidator(control)) {
            control.setValidators([control.validator, Validators.requiredTrue]);
        } else {
            control.setValidators(control.validator);
        }
    }

...

    /**
     * Returns whether checkbox is required
     * @param abstractControl control assigned to component
     */
    hasRequiredValidator(abstractControl: AbstractControl): boolean {
        if (abstractControl.validator) {
            const validator = abstractControl.validator({} as AbstractControl);
            if (validator && validator.required) {
                return true;
            }
        }
        return false;
    }

1 个答案:

答案 0 :(得分:2)

您可以使用index获取切片元素:

{{ $length := len $urlArray }}
first - {{index $urlArray 0}}

但是最后一个难度更大,因为您必须获取索引$length - 1,并且模板中不允许进行算术运算。

但是您可以将go函数公开给模板:

func first(s []string) string {
  if len(s) == 0 {
    return ""
  }
  return s[0]
}

func last(s []string) string {
  if len(s) == 0 {
    return ""
  }
  return s[len(s) - 1]
}

const tmpl = `first - {{ first $urlArray }}, last - {{ last $urlArray }}`

t := template.Must(template.New("").Funcs(template.FuncMap{"first": first, "last": last}).Parse(tmpl))