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

Macros are not callable when transported to other state #329

Open
mitsuhiko opened this issue Aug 17, 2023 · 4 comments
Open

Macros are not callable when transported to other state #329

mitsuhiko opened this issue Aug 17, 2023 · 4 comments
Labels
enhancement New feature or request

Comments

@mitsuhiko
Copy link
Owner

Description

Originally macros could not leak out of the calling template, which is why the implementation could get away with indexing into the instructions of the state. Now however you can export the macros by looking them up on the state after rendering. This means that a macro can be called from a state that does not have the macro's instructions stored.

Reproduction steps

#[test]
fn test_macro_passing() {
    let env = Environment::new();
    let tmpl = env
        .template_from_str("{% macro m(a) %}{{ a }}{% endmacro %}")
        .unwrap();
    let (_, state) = tmpl.render_and_return_state(()).unwrap();
    let m = state.lookup("m").unwrap();
    assert_eq!(m.get_attr("name").unwrap().as_str(), Some("m"));
    let rv = m.call(&state, args!(42)).unwrap();
    assert_eq!(rv.as_str(), Some("42"));

    // panics!
    let empty_state = env.empty_state();
    let rv = m.call(&empty_state, args!(42)).unwrap();
    assert_eq!(rv.as_str(), Some("42"));
}
@mitsuhiko
Copy link
Owner Author

Macros are already kind of odd in how they work. Because there is no refcounting system or else for instructions (and template source), it's not possible for macros to hold a reference at the moment. The best I can do for now is to prevent the panic and error instead.

@mitsuhiko mitsuhiko added enhancement New feature or request and removed bug Something isn't working labels Aug 17, 2023
@mitsuhiko
Copy link
Owner Author

This is even harder to fix now that closures are linked to the original state. When a state is removed, the closures are cleared to avoid circular references. See #359

@mitsuhiko
Copy link
Owner Author

Came up also in this context: #430

@mitsuhiko
Copy link
Owner Author

Also came up here: #463

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

No branches or pull requests

1 participant