feat: added more abilities to htmlx.

This commit is contained in:
Andrey Parhomenko 2024-06-09 21:42:20 +05:00
parent c989b004d9
commit 02a0cb3a01
2 changed files with 79 additions and 25 deletions

View file

@ -1,15 +1,26 @@
fmt := import("fmt")
html := import("html").new_render()
added := html.ul()
for i in [1, 2, 3, 4, 5] {
added.add(html.li().body(i))
}
fmt.println(
html.html({
lang: "en"
}).body(
html.head(),
html.head().body(
html.link({
rel: "stylesheet",
href: "/web/main.css"
}).final()
),
html.body().body(
html.p().body(
">>>shit"
)
)
),
added
)
)

View file

@ -19,6 +19,7 @@ type Element struct {
// The value makes sense only if
// the tag is the "raw"
Content string
Final bool
}
func (el *Element) TypeName() string {
@ -40,6 +41,10 @@ func (el *Element) String() string {
}
fmt.Fprint(&b, ">")
if el.Final {
return b.String()
}
for _, child := range el.Children {
if child == nil {
continue
@ -51,9 +56,56 @@ func (el *Element) String() string {
return b.String()
}
func (el *Element) Body(els ...*Element) *Element {
func MakeElements(args ...tengo.Object) ([]*Element, error) {
s := []*Element{}
for _, arg := range args {
el, ok := arg.(*Element)
if !ok {
str, ok := tengo.ToString(arg)
if !ok {
return nil, tengo.ErrInvalidArgumentType{
}
}
s = append(s, &Element{
Tag: RawTag,
Content: str,
})
}
s = append(s, el)
}
return s, nil
}
func (el *Element) SetBody(
args ...tengo.Object,
) (tengo.Object, error) {
els, err := MakeElements(args...)
if err != nil {
return nil, err
}
el.Children = els
return el
return el, nil
}
func (el *Element) Add(
args ...tengo.Object,
) (tengo.Object, error) {
s, err := MakeElements(args...)
if err != nil {
return nil, err
}
el.Children = append(el.Children, s...)
return el, nil
}
func (el *Element) SetFinal(
args ...tengo.Object,
) (tengo.Object, error) {
if len(args) > 0 {
return nil, tengo.ErrWrongNumArguments
}
el.Final = true
return el, nil
}
func (el *Element) IndexGet(
@ -67,27 +119,18 @@ func (el *Element) IndexGet(
switch arg {
case "body" :
return &tengo.UserFunction{
Name: "Element.Body",
Value: func(
args ...tengo.Object,
) (tengo.Object, error) {
s := []*Element{}
for _, arg := range args {
el, ok := arg.(*Element)
if !ok {
str, ok := tengo.ToString(arg)
if ok {
s = append(s, &Element{
Tag: RawTag,
Content: str,
})
}
continue
}
s = append(s, el)
}
return el.Body(s...), nil
},
Name: "element.body",
Value: el.SetBody,
}, nil
case "final" :
return &tengo.UserFunction{
Name: "element.final",
Value: el.SetFinal,
}, nil
case "add" :
return &tengo.UserFunction{
Name: "element.add",
Value: el.Add,
}, nil
}
return nil, nil