Skip to content

Commit

Permalink
Add boolean version of setAttr (#240)
Browse files Browse the repository at this point in the history
* vdom: Add setAttr proc with boolean val

* README: Tweak description of boolean attributes

* Use cstring(nil) approach in boolean setAttr
  • Loading branch information
ryukoposting committed Mar 23, 2023
1 parent fffaa6b commit 6609c32
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
13 changes: 13 additions & 0 deletions karax/vdom.nim
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,19 @@ proc setAttr*(n: VNode; key: kstring; val: kstring = "") =
n.attrs.add key
n.attrs.add val

proc setAttr*(n: VNode, key: kstring, val: bool) =
when defined(js):
n.setAttr(key, if val: cstring"" else: cstring(nil))
else:
if val:
n.setAttr(key, "")
else:
for i in countup(0, n.attrs.len-2, 2):
if n.attrs[i] == key:
n.attrs.delete i+1
n.attrs.delete i
break

proc getAttr*(n: VNode; key: kstring): kstring =
for i in countup(0, n.attrs.len-2, 2):
if n.attrs[i] == key: return n.attrs[i+1]
Expand Down
19 changes: 19 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -348,6 +348,25 @@ setError password, password & " must not be empty"
```
There are likely more elegant solutions to this problem.

## Boolean attributes

Some HTML attributes don't have meaningful values; instead, they are treated like
a boolean whose value is `false` when the attribute is not set, and `true` when
the attribute is set to any value. Some examples of these attributes are `disabled`
and `contenteditable`.

In Karax, these attributes can be set/cleared with a boolean value:

```nim
proc submitButton(dataIsValid: bool): VNode =
buildHtml(tdiv):
button(disabled = not dataIsValid):
if dataIsValid:
text "Submit"
else:
text "Cannot submit, data is invalid!"
```

## Routing


Expand Down

0 comments on commit 6609c32

Please sign in to comment.