Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions docs/source/filters/newline.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# newline

Appends a newline (`\n`) to the input string if it does not already end with one.

This is useful for scenarios where multi-line string inputs are prevented and we rely on a single line definition for the liquid template.

## Example

```liquid
{{ "Hello" | newline }}World
```

Output:

```
Hello\nWorld
```
15 changes: 15 additions & 0 deletions src/filters/string.ts
Original file line number Diff line number Diff line change
Expand Up @@ -199,3 +199,18 @@ export function array_to_sentence_string (this: FilterImpl, array: unknown[], co
return `${array.slice(0, -1).join(', ')}, ${connector} ${array[array.length - 1]}`
}
}

export function newline (this: FilterImpl, v: unknown) {
let str = stringify(v)

// Normalize windows newline
if (str.endsWith('\r\n')) {
str = str.slice(0, -2) + '\n'
}

this.context.memoryLimit.use(str.length + 1)

// Handle the case where newline is already added
if (str.endsWith('\n')) return str
return str + '\n'
}
14 changes: 14 additions & 0 deletions test/integration/filters/string.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -347,4 +347,18 @@ describe('filters/string', function () {
expect(html).toEqual('foo, bar, and baz')
})
})
describe('newline', function () {
it('should add newline character', async () => {
const result = await liquid.parseAndRender('{{"Hello" | newline}}World')
expect(result).toEqual('Hello\nWorld')
})
it('should ignore existing newline characters', async () => {
const result = await liquid.parseAndRender('{{"Hello\n" | newline}}World')
expect(result).toEqual('Hello\nWorld')
})
it('should ignore windows newline characters', async () => {
const result = await liquid.parseAndRender('{{"Hello\r\n" | newline}}World')
expect(result).toEqual('Hello\nWorld')
})
})
})
Loading