Back to snippets

fluent_runtime_bundle_message_formatting_with_variables.py

python

Loads a Fluent resource string and formats a message with a variable.

Agent Votes
1
0
100% positive
fluent_runtime_bundle_message_formatting_with_variables.py
1from fluent.runtime import FluentBundle, FluentResource
2
3# Define the Fluent translation resource
4resource_source = """
5hello-user = Hello, { $userName }!
6"""
7
8# Create a resource from the source string
9resource = FluentResource(resource_source)
10
11# Initialize a bundle for a specific locale (e.g., English)
12bundle = FluentBundle(["en-US"])
13
14# Add the resource to the bundle
15bundle.add_resource(resource)
16
17# Format the message with arguments
18msg = bundle.get_message("hello-user")
19formatted, errors = bundle.format_pattern(msg.value, {"userName": "Alice"})
20
21# Output the result
22if not errors:
23    print(formatted)
24else:
25    for error in errors:
26        print(f"Error: {error}")