Home > database >  django-component - passing string instead of context variable
django-component - passing string instead of context variable

Time:02-18

Having trouble passing context variable to a django-component

View:

labels = "'January','February','March','April','May','June'"    
    data = "69, 10, 5, 2, 20, 30"
    colors = "'#3e95cd', '#8e5ea2','#3cba9f','#e8c3b9','#c45850','#a45350'"
    
    context = { 'title': title, 'language': langCode, 'clabels':labels, 'cdata':data, 'ccolors':colors}
    return render(request, "reports/dashboard.html", context)

In Template:

<div >{% component "simplechart" width="980" height="300" chartid="chart1" title="We are testing" clabels='{{ clabels }}' cdata="{{ cdata }}" ccolors="{{ ccolors }}" type="bar" %}</div>

Components.py

@component.register("simplechart")
class SimpleChart(component.Component):
    # Note that Django will look for templates inside `[your app]/components` dir
    # To customize which template to use based on context override get_template_name instead
    template_name = "simplechart/simplechart.html"

    # This component takes three parameters
    def get_context_data(self, width, height, chartid, title, clabels,cdata,ccolors, type):
        print("CHART GET CONTEXT")
        print(cdata)
        print(clabels)
        return {
            "width": width,
            "height": height,
            "chartid": chartid,
            "title": title,
            "clabels": clabels,
            "cdata": cdata,
            "ccolors": ccolors,
            "type": type
        }

    class Media:
        css = {
                'all': ('css/simplecard.css')
        }
        js = 'js/cmx_chart.js'

The debug print statements output:

CHART GET CONTEXT
{{cdata}}
{{clabels}}

It is passing in the litereal string, not replacing with context variable passed in from the view. Any ideas what I'm doing wrong?

CodePudding user response:

The problem is that you are passing a string: "{{ clabels }}". Delete the quotes and the "{{" inside the tag. So:

{% component "simplechart" width="980" height="300" chartid="chart1" title="We are testing" clabels=clabels cdata=cdata ccolors=ccolors type="bar" %}
  • Related