f-strings
v0.0.0
Published
Tagged template function to write readable multi-line strings with embedded if-else conditions and automatic dedentation
Readme
f-strings
f-strings provides a tagged template f that allows you to write readable multi-line strings with embedded if-else conditions and automatic dedentation.
Installation
npm install f-stringsUsage
Use If, Else, and EndIf expressions to include conditional content.
import { f, If, Else, EndIf } from 'f-strings';
const history = [
{ role: 'user', content: 'Hello' },
{ role: 'assistant', content: 'Hi there!' },
];
const question = 'What is the capital of France?';
const prompt = f`
You are a helpful assistant.
${If(history.length)}
Conversation history:
${history.map((msg) => `- ${msg.role}: ${msg.content}`)}
${Else}
No conversation history.
${EndIf}
User question:
${question}
`;
console.log(message);You are a helpful assistant.
Conversation history:
- user: Hello
- assistant: Hi there!
User question:
What is the capital of France?Dedentation
Strips indentation from multi-line strings.
import { f, If, EndIf } from 'f-strings';
const prompt = f`
Hello
World!
How are you?
I'm good, thank you!
`;
console.log(dedented);Hello
World!
How are you?
I'm good, thank you!Lazyness
Expressions can be lazily evaluated, so you can use functions to generate content only when needed.
import { f, If, EndIf } from 'f-strings';
const messages = await getMessages();
const prompt = f`
${If(messages.length)}
You have ${messages.length} messages:
${() => messages.map((msg) => `- ${msg}`)}
${Else}
No messages.
${EndIf}
`;
console.log(prompt);You have 1000 messages:
- Message 1
- Message 2
...
- Message 1000API
f - Tagged Template Function
f`template ${value} string`If(condition) - Conditional Block
Starts a conditional block. Includes the following content if the condition is truthy.
const text = f`
${If(condition)}
content when true
${EndIf}
`;Else() - Alternative Block
Starts an alternative block. Includes the following content if the condition is falsy.
![NOTE]
Elsecan be used without calling it as a function:${Else}or${Else()}.
const text = f`
${If(condition)}
content when true
${Else}
content when false
${EndIf}
`;EndIf - End Conditional
Marks the end of a conditional block. Required for every If.
![NOTE]
EndIfcan be used without calling it as a function:${EndIf}or${EndIf()}.
License
MIT
