| 1 | The CobraCore class provides methods to encode and decode URLs and HTML. For example: |
| 2 | {{{ |
| 3 | #!cobra |
| 4 | s = 'x < y' |
| 5 | assert CobraCore.htmlEncode(s) == 'x < y' |
| 6 | }}} |
| 7 | |
| 8 | Additionally, there is a class called `Html` for holding text that already represents Html. The `.htmlEncode` method is cognizant of it: |
| 9 | {{{ |
| 10 | #!cobra |
| 11 | text = Html('<p>Hello.</p>') |
| 12 | assert CobraCore.htmlEncode(text) == '<p>Hello.</p>' |
| 13 | }}} |
| 14 | |
| 15 | Here is a summary of what is available: |
| 16 | {{{ |
| 17 | #!cobra |
| 18 | namespace Cobra.Core |
| 19 | |
| 20 | class CobraCore |
| 21 | |
| 22 | shared |
| 23 | |
| 24 | def htmlEncode(obj as Object?) as String |
| 25 | """ |
| 26 | Return the HTML encoded version of the given object. |
| 27 | Returns the contents of the object if it is an instance of Html. |
| 28 | This is useful to display a plain ASCII text string on a web page. |
| 29 | """ |
| 30 | if obj is nil, return '' |
| 31 | if obj inherits Html, return obj.contents |
| 32 | return .htmlEncode(obj.toString) |
| 33 | |
| 34 | def htmlEncode(s as String?) as String |
| 35 | """ |
| 36 | Return the HTML encoded version of the given string. |
| 37 | This is useful to display a plain ASCII text string on a web page. |
| 38 | """ |
| 39 | test |
| 40 | assert .htmlEncode('foo') == 'foo' |
| 41 | assert .htmlEncode('3 < 5') == '3 < 5' |
| 42 | |
| 43 | def htmlDecode(s as String?) as String |
| 44 | """ |
| 45 | Return the HTML decoded version of the given string. |
| 46 | """ |
| 47 | test |
| 48 | assert .htmlDecode('foo') == 'foo' |
| 49 | assert .htmlDecode('3 < 5') == '3 < 5' |
| 50 | |
| 51 | def urlEncode(s as String?) as String |
| 52 | """ |
| 53 | Return a version of the string encoded for and safe to use in URLs. |
| 54 | """ |
| 55 | |
| 56 | def urlDecode(s as String?) as String |
| 57 | |
| 58 | |
| 59 | class Html |
| 60 | """ |
| 61 | Represents HTML that doesn't need to be encoded. |
| 62 | Html.toString returns the contents as-is. |
| 63 | """ |
| 64 | cue init(contents as String) |
| 65 | base.init |
| 66 | _contents = contents |
| 67 | get contents from var as String |
| 68 | def toString as String is override |
| 69 | return _contents |
| 70 | }}} |
| 71 | |
| 72 | See also: CobraCore, WebDevelopment, LibraryTopics |