diff --git a/django_components/component.py b/django_components/component.py
index f77a6e76..2db337e9 100644
--- a/django_components/component.py
+++ b/django_components/component.py
@@ -1,12 +1,30 @@
+from django.template.loader import render_to_string
from .component_registry import ComponentRegistry, AlreadyRegistered, NotRegistered # NOQA
class Component(object):
+ CSS_TEMPLATE = ''
+ JS_TEMPLATE = ''
+
def __init__(self):
self._media = self.Media()
def context(self):
return {}
+ def render_dependencies(self):
+ out = []
+
+ for css_media, css_path in self._media.css.items():
+ out.append(Component.CSS_TEMPLATE.format(css_path, css_media))
+
+ for js_path in self._media.js:
+ out.append(Component.JS_TEMPLATE.format(js_path))
+
+ return "\n".join(out)
+
+ def render(self, *args, **kwargs):
+ return render_to_string(self._media.template, self.context(*args, **kwargs))
+
class Media:
template = None
css = {}
diff --git a/tests/templates/simple_template.html b/tests/templates/simple_template.html
new file mode 100644
index 00000000..3f2b5995
--- /dev/null
+++ b/tests/templates/simple_template.html
@@ -0,0 +1 @@
+Variable: {{ variable }}
diff --git a/tests/test_component.py b/tests/test_component.py
index f8ac9b8d..9b3b10a2 100644
--- a/tests/test_component.py
+++ b/tests/test_component.py
@@ -1,23 +1,38 @@
+from textwrap import dedent
import unittest
+import django
+from django.conf import settings
from django_components import component
class SimpleComponent(component.Component):
- def context(self, variable):
+ def context(self, variable=None):
return {
"variable": variable,
}
class Media:
- template = "template.html"
+ template = "simple_template.html"
css = {"all": "style.css"}
js = ("script.js",)
class ComponentRegistryTest(unittest.TestCase):
- def test_simple_component(self):
+ def setUp(self):
+ settings.configure(
+ TEMPLATES=[{
+ 'BACKEND': 'django.template.backends.django.DjangoTemplates',
+ 'DIRS': ["tests/templates/"],
+ }]
+ )
+ django.setup()
+ def test_simple_component(self):
comp = SimpleComponent()
- self.assertEqual(comp.context("test"), {"variable": "test"})
- self.assertEqual(comp._media.template, "template.html")
- self.assertEqual(comp._media.css, {"all": "style.css"})
- self.assertEqual(comp._media.js, ("script.js",))
+ self.assertEqual(comp.render_dependencies(), dedent("""
+
+
+ """).strip())
+
+ self.assertEqual(comp.render(variable="test"), dedent("""
+ Variable: test
+ """).lstrip())