html.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. package htmlx
  2. import "github.com/d5/tengo/v2"
  3. var Module = map[string] tengo.Object{
  4. "Renderer" : &tengo.BuiltinFunction{
  5. Name: "Renderer",
  6. Value: func(args ...tengo.Object) (tengo.Object, error){
  7. ret := &Renderer{}
  8. return ret, nil
  9. },
  10. },
  11. }
  12. type Renderer struct{
  13. tengo.ObjectImpl
  14. }
  15. func (html *Renderer) TypeName() string {
  16. return "htmlx.Renderer"
  17. }
  18. func (html *Renderer) String() (string) {
  19. return "htmlx.Renderer{...}"
  20. }
  21. /*
  22. html.div({
  23. id: "some-el-id",
  24. value: "shit value"
  25. }).body(
  26. html.raw("cock "),
  27. html.strong("something")
  28. )
  29. */
  30. func (html *Renderer) IndexGet(
  31. index tengo.Object,
  32. ) (tengo.Object, error) {
  33. str, ok := tengo.ToString(index)
  34. if !ok {
  35. return nil, tengo.ErrInvalidIndexValueType
  36. }
  37. fn := func(args ...tengo.Object) (tengo.Object, error) {
  38. if len(args) > 1 {
  39. return nil, tengo.ErrWrongNumArguments
  40. }
  41. var arg tengo.Object
  42. if len(args) == 1 {
  43. arg = args[0]
  44. }
  45. if arg == nil {
  46. return &Element{
  47. Tag: str,
  48. }, nil
  49. }
  50. if can := arg.CanIterate() ; !can {
  51. return nil, tengo.ErrInvalidArgumentType{
  52. Name: "first",
  53. Expected: "iterable",
  54. Found: arg.TypeName(),
  55. }
  56. }
  57. attr := map[string] string{}
  58. iter := arg.Iterate()
  59. for iter.Next() {
  60. key, val := iter.Key(), iter.Value()
  61. skey, ok := tengo.ToString(key)
  62. if !ok {
  63. return nil, tengo.ErrInvalidArgumentType{
  64. Name: "attribute(key)",
  65. Expected: "stringer",
  66. Found: key.TypeName(),
  67. }
  68. }
  69. sval, ok := tengo.ToString(val)
  70. if !ok {
  71. return nil, tengo.ErrInvalidArgumentType{
  72. Name: "attribute(value)",
  73. Expected: "stringer",
  74. Found: val.TypeName(),
  75. }
  76. }
  77. attr[skey] = sval
  78. }
  79. return &Element{
  80. Tag: str,
  81. Attr: attr,
  82. }, nil
  83. }
  84. return &tengo.UserFunction{
  85. Name: str,
  86. Value: fn,
  87. }, nil
  88. }