Opened 7 years ago

Last modified 4 months ago

#6378 new New feature

Capture arbitrary output as a template variable

Reported by: kcarnold Owned by: carljm
Component: Template system Version: master
Severity: Normal Keywords:
Cc: kenneth.arnold@…, charette.s@…, oss@…, loic84, cmawebsite@… Triage Stage: Accepted
Has patch: yes Needs documentation: yes
Needs tests: no Patch needs improvement: yes
Easy pickings: no UI/UX: no

Description

I'd like to suggest including http://www.djangosnippets.org/snippets/545/ in Django because of its generality and simplicity, compared to adding the equivalent functionality to each individual tag, or trying to use the block tag for this purpose as has been suggested.

Attachments (1)

6378-into.diff (3.8 KB) - added by ericholscher 6 years ago.
Initial patch that is a bit rough.

Download all attachments as: .zip

Change History (27)

comment:1 Changed 7 years ago by Simon Greenhill <dev@…>

  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset
  • Triage Stage changed from Unreviewed to Design decision needed

comment:2 Changed 7 years ago by mtredinnick

Search out the discussions from last year on django-dev where we were talking about how to extend the "with" tag to work with tags, not just variables. I don't think any real consensus was reached, but something that is a block-based version of "with" (and spelt more or less the same) is much more likely to have legs here. Making people learn yet another tag that isn't related to the existing thing that works like this ("with") isn't good API.

comment:3 Changed 7 years ago by kcarnold

  • Cc kenneth.arnold@… added

comment:4 Changed 6 years ago by ericholscher

@Malcolm: I couldn't find the discussion from django-dev, "with" is stripped out by google's search. Anyway, here is an idea I've had about this functionality.

How about implementing this as an optional "into" (colored appropriately) where you could have a statement along the lines of

{% with person.get_absolute_url as main_url into content %}
check out my page: {{ main_url }}
{% endwith %}

This would then instead of outputting the included block into the template, stuff it into the content variable.

However, this doesn't cover the situation where you don't want to put a new variable into the context, but you simply want to put that output into a variable. Something along the lines of {% with [None|magic_word] into content %} was the best I could come up with.

I think that capturing the output of a block is a different operation than including a variable into the inner block's context. Maybe a better solution would be to have a {% withblock as content %} tag that is a counterpart to the "with" tag.

It feels like this functionality shouldn't go in two places, so maybe "withblock" would also have the ability to set the context variables inside. Seems bad to have the functionality in two places either way. The best situation would probably be a sane way to define the capture syntax on the "with" tag, without settings the context variable.

comment:5 Changed 6 years ago by ericholscher

I wrote up a patch with this code in it. It has tests, but the test:

            'with04': ('{{ content }}-{% with dict.key as key into content %}{{ key }}{% endwith %}-{{ content }}', {'dict': {'key': 50}}, '--50'),

Is failing only when

Template test (TEMPLATE_STRING_IF_INVALID='INVALID'): with04 -- FAILED. Expected '--50', got u'50--50'

When the TEMPLATE_STRING_IF_INVALID="", it works fine and only inserts into the context afterwards. When it is set to INVALID, it appears to break. I don't really understand this but will investigate further.

Changed 6 years ago by ericholscher

Initial patch that is a bit rough.

comment:7 Changed 6 years ago by nathan

This would be a great addition to the template language. All to often I add "wrapper" blocks to cancel out HTML so its style doesn't effect the layout. This leads to added template code in child templates.

I've always seen {% with %} more for reassigning variables but if we can augment it to hand code snippets that would be nice but I don't mind learning new tags :)

Scenario: http://gist.github.com/221803

comment:8 Changed 6 years ago by jtinsky

I agree this would be helpful in a wide variety of situations. "{% with %}" doesn't always get the job done.

comment:9 Changed 5 years ago by nathan

Another use-case that would be handy if you wanted to reuse block content:

{% capture as title %}
  {% block title %}{% endblock %}
{% endcapture %}

<html>
    <head>
        <title>{{ title }}</title>
    </head>
    <body>
        <h1>{{ title }}</h1>
    </body>
</html>

comment:10 Changed 4 years ago by julien

  • Has patch set
  • Needs documentation set
  • Patch needs improvement set
  • Severity set to Normal
  • Type set to New feature

Patch needs to be updated as the proposed API really isn't suitable. The "capture as" tag above would certainly stand a better chance. See also #14262 for a related feature request.

comment:11 Changed 4 years ago by carljm

  • Easy pickings unset
  • Resolution set to wontfix
  • Status changed from new to closed
  • UI/UX unset

This needs a stronger use-case justification. Many of the use-cases for this are indications that the template should be re-structured, or an {% include %} could be used instead. Capturing output like this is yet another entirely different mental model for organizing and reusing template code, and we already have at least two of those - we need strong justification to add another to core (especially since it can work just fine as an external snippet/library).

comment:12 Changed 3 years ago by anonymous

Does this justify as a general use-case?

{% capture as subject %}
	{% if user = request.user %}My{% else %}{{ user.first_name }}'s{% endif %}
{% endcapture %}
...
<div id="profile-photo">
	My Photo
	<img />
</div>
...
<div id="profile-friends">
	<h3>{{ subjects }} Friends</h3>
	List of friends...
</div>
<div id="profile-groups">
	<h3>{{ subjects }} Groups</h3>
	List of groups...
</div>
<div id="profile-friends">
	<h3>{{ subjects }} Friends</h3>
	List of friends...
</div>
...

comment:13 Changed 3 years ago by anonymous

  • Resolution wontfix deleted
  • Status changed from closed to reopened

comment:14 Changed 3 years ago by anonymous

  • Owner changed from nobody to carljm
  • Status changed from reopened to new

comment:15 Changed 3 years ago by carljm

  • Triage Stage changed from Design decision needed to Accepted

I've changed my opinion on this; I do think there are cases where the "capture" model is the appropriate one, and it ought to be built-in. Particularly in cases like the above example, where a non-trivial block of template should be repeated. Inheritance doesn't support this. Includes could be used, but impose a significant performance penalty, both for doing the include and because the repeated block has to be evaluated multiple times. Otherwise you're reduced to a custom template tag.

Marking accepted, pending any argument from other core developers :-)

comment:16 follow-up: Changed 3 years ago by aaugustin

The use case doesn't seem that compelling to me — the logic calculating "subject" /could/ be handled in the view.

That said, I don't have a strong opinion on this feature.

comment:17 in reply to: ↑ 16 Changed 3 years ago by carljm

Replying to aaugustin:

The use case doesn't seem that compelling to me — the logic calculating "subject" /could/ be handled in the view.

It could be, but it shouldn't be. Display logic in the view is ugly, just like business logic in a template. And HTML in strings in the view is even uglier.

comment:18 Changed 3 years ago by charettes

  • Cc charette.s@… added

comment:19 Changed 3 years ago by aaron@…

Another use-case

cmsplugin_zinnia/templates/cmsplugin_zinnia/entry_detail.html:

{% load i18n placeholder_tags %}
{% for entry in entries %}
{% captureas content %}
{% render_placeholder entry.content_placeholder %}
{% endpatureas %}
  {% with object=entry object_content=content continue_reading=1 %}
  {% include "zinnia/_entry_detail.html" %}
  {% endwith %}
{% empty %}
  <p class="notice">{% trans "No entries yet." %}</p>
{% endfor %}

This is because rendering entry.content_placeholder generates sekizai_tags that need to get picked up.

comment:20 Changed 3 years ago by oss@…

  • Cc oss@… added

comment:21 Changed 2 years ago by CollinAnderson

  • Cc cmawebsite@… added

This would make the template language turing-complete. I would use it. :) You could even just name the tag var. Though we may be opening a can of worms :)

Last edited 2 years ago by CollinAnderson (previous) (diff)

comment:22 Changed 13 months ago by loic84

  • Cc loic84 added

comment:23 Changed 10 months ago by anonymous

Any work on this ?

comment:24 Changed 4 months ago by collinanderson

  • Cc cmawebsite@… removed

Btw, if we did this, we would need to remove the line in philosophy docs about intentionally not allowing assignment to variables.

https://docs.djangoproject.com/en/dev/misc/design-philosophies/#don-t-invent-a-programming-language

comment:25 Changed 4 months ago by collinanderson

  • Cc cmawebsite@… added

comment:26 Changed 4 months ago by prestontimmons

Isn't the assignment to variables line kinda wrong anyway? Most template tags accept the "as" argument, and the with tag also assigns variables, albeit in a scoped manner.

Note: See TracTickets for help on using tickets.
Back to Top