🔍 Code Extractor

function render_template_v1

Maturity: 54

A simple template rendering function that replaces placeholders in a template string with corresponding values from a dictionary using string replacement.

File:
/tf/active/vicechatdev/CDocs single class/utils/notifications.py
Lines:
643 - 658
Complexity:
simple

Purpose

This function provides basic template rendering functionality by replacing placeholders in the format '{key}' with their corresponding values from a data dictionary. It's useful for generating dynamic text content such as email bodies, notifications, reports, or any text-based output that requires variable substitution. Unlike more sophisticated templating engines (like Jinja2), this uses simple string replacement, making it lightweight but limited to basic placeholder substitution without support for conditionals, loops, or filters.

Source Code

def render_template(template: str, data: Dict[str, Any]) -> str:
    """
    Render template with data using simple placeholder replacement.
    
    Args:
        template: Template string
        data: Data to populate template
        
    Returns:
        Rendered template
    """
    result = template
    for key, value in data.items():
        placeholder = '{' + key + '}'
        result = result.replace(placeholder, str(value))
    return result

Parameters

Name Type Default Kind
template str - positional_or_keyword
data Dict[str, Any] - positional_or_keyword

Parameter Details

template: A string containing placeholders in the format '{key}' where 'key' corresponds to keys in the data dictionary. The template can contain multiple placeholders, and the same placeholder can appear multiple times. Any text not matching the placeholder pattern will remain unchanged.

data: A dictionary mapping placeholder names (keys) to their replacement values. Keys should be strings matching the placeholder names in the template (without the curly braces). Values can be of any type but will be converted to strings using str(). If a placeholder in the template has no corresponding key in the data dictionary, it will remain unchanged in the output.

Return Value

Type: str

Returns a string with all matching placeholders replaced by their corresponding values from the data dictionary. Placeholders are replaced with the string representation of their values. If a placeholder in the template doesn't have a matching key in the data dictionary, it remains as-is in the returned string.

Required Imports

from typing import Dict, Any

Usage Example

# Basic usage
template = "Hello {name}, your order #{order_id} has been {status}."
data = {
    "name": "John Doe",
    "order_id": 12345,
    "status": "shipped"
}
result = render_template(template, data)
print(result)
# Output: Hello John Doe, your order #12345 has been shipped.

# Example with missing placeholder
template2 = "Welcome {user}! Your balance is {balance}."
data2 = {"user": "Alice"}
result2 = render_template(template2, data2)
print(result2)
# Output: Welcome Alice! Your balance is {balance}.

# Example with repeated placeholders
template3 = "{greeting} {name}! {greeting} again!"
data3 = {"greeting": "Hello", "name": "Bob"}
result3 = render_template(template3, data3)
print(result3)
# Output: Hello Bob! Hello again!

Best Practices

  • This function does not handle missing keys gracefully - placeholders without corresponding data keys will remain in the output. Consider validating that all required keys exist in the data dictionary before calling this function.
  • All values are converted to strings using str(), so ensure that your data values have appropriate string representations (especially for custom objects).
  • This function does not escape special characters or handle nested placeholders. For complex templating needs with conditionals, loops, or filters, consider using a full-featured templating engine like Jinja2.
  • The function performs simple string replacement, so if your data values contain text that looks like placeholders (e.g., '{something}'), they won't be processed recursively.
  • For security-sensitive applications (like HTML rendering), be aware that this function does not perform any sanitization or escaping of the input values. You should sanitize data before passing it to this function if needed.
  • The function iterates through all key-value pairs in the data dictionary, so performance may degrade with very large dictionaries, though this is unlikely to be an issue for typical use cases.

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function render_template 83.2% similar

    Renders a template string by replacing placeholders with data values and processing conditional blocks (if/endif tags).

    From: /tf/active/vicechatdev/CDocs/utils/notifications.py
  • function test_template_with_data 64.3% similar

    Tests a template file by replacing placeholders with test data and validates that all required placeholders have been filled, excluding known conditional placeholders.

    From: /tf/active/vicechatdev/test_comprehensive_templates.py
  • function generate_document_from_template 55.8% similar

    Generates a document from a template by populating it with provided data, returning the document content as bytes or None if generation fails.

    From: /tf/active/vicechatdev/CDocs/utils/document_processor.py
  • function api_load_template_v1 42.5% similar

    Flask API endpoint that loads and returns instruction templates from a RAG (Retrieval-Augmented Generation) engine based on the provided template name.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function demo_placeholder_parsing 42.4% similar

    Demonstrates the parsing of graphics placeholders embedded in text by extracting and displaying placeholder metadata including type, description, ID, and parameters.

    From: /tf/active/vicechatdev/e-ink-llm/demo_hybrid_mode.py
← Back to Browse