Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Question: Is there a better way to render blocks? #330

Open
wombat2k opened this issue Nov 7, 2022 · 0 comments
Open

Question: Is there a better way to render blocks? #330

wombat2k opened this issue Nov 7, 2022 · 0 comments

Comments

@wombat2k
Copy link

wombat2k commented Nov 7, 2022

I'm trying to duplicate the functionality of Django-render-block. Basically I want the ability to only render a specific block in a template. I'm relatively new to Swift, so wasn't expecting much, but to my surprise, I got it to work like so

public extension Template {
    func render(block: String, _ context: Context) throws -> String {
        let context = context
        var append = false
        var collectedTokens = [Token]()
        
        for token in tokens {
            if token.contents.description.starts(with: "block \(block)") {
                append = true
            }
            
            if token.contents.description == "endblock \(block)" {
                break
            }
            
            if append {
                collectedTokens.append(token)
            }
        }

        let parser = TokenParser(tokens: collectedTokens, environment: context.environment)
        let nodes = try parser.parse()
        return try renderNodes(nodes, context)
    }
}

Obviously this is very crude and relies on a textual representation of the token, but it does exactly what I need and as a bonus it worked with custom tags. Is there a better more elegant way to achieve this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant