Is there a way to pass a variable to an 'extended' template in Django?

I suspect that block is what you are looking for in the first place.

Form your block inside the base template like this:

{% block sidebar_wrapper %}
    {% if sidebar %}
    <div class="width{{sidebar_width}}">
        {% block sidebar %}{% endblock %}
    </div>
    {% endif %}
{% endblock sidebar_wrapper%}

And on your child template:

{% extends 'layout.html' %}
{% block sidebar_wrapper %}
    {% with sidebar=True sidebar_width=4 %}
        {{ block.super }}
    {% endwith%}
{% endblock sidebar_wrapper%}

What you need is an include template tag. You can include a template in another template and render that with specific context.

{% include 'layout.html' with sidebar=True sidebar_width=4 %}

Check docs here: https://docs.djangoproject.com/en/2.2/ref/templates/builtins/#include