Why one template is a useful architecture
Personalised landing pages often begin with a practical need: different visitors should see different messages, products, offers or calls to action, while the underlying page structure remains consistent. Creating one HTML file for every variation can work for a small experiment, but it soon creates duplicated markup, inconsistent fixes and difficult content reviews.
Django provides a better separation between presentation and data. A view can determine which audience, campaign or product is relevant, then pass that information to one template. The template renders the shared layout and displays values from the context. This approach keeps the visual structure in one place while allowing the content to change according to well-defined rules.
The goal is not to put every business rule into the template. A maintainable implementation gives each layer a clear responsibility:
- The URL identifies the requested resource or campaign.
- The view validates the request and gathers the required data.
- Models or service functions provide reliable content.
- The template presents that content without repeating application logic.
- Reusable template components handle recurring elements such as buttons, feature cards and navigation.
Personalisation can therefore mean selecting a campaign, showing a product-specific message, adapting a page to a language or presenting content for a known customer segment. The same design principle applies in each case: use data to vary the output, rather than copying the complete page.
Choose the personalisation input before writing code
A landing page can be personalised from several types of input. The safest choice depends on the purpose of the page and the quality of the information available.
| Input | Typical use | Main consideration |
|---|
| Path parameter | A page for a campaign, product or category | Validate that the requested object exists and is public |
| Query parameter | Tracking a campaign or selecting a non-sensitive variation | Do not trust the value as permission or as safe HTML |
| Authenticated user | Showing account-specific information | Check authentication and object-level authorisation |
| Session value | Remembering a visitor's selected language or preference | Define expiry and avoid storing sensitive data unnecessarily |
| Cookie | Remembering a consented preference | Respect consent, privacy requirements and secure cookie settings |
A path parameter is often the clearest option for public campaign pages. For example, a URL containing a campaign slug expresses which landing page the visitor requested. A query parameter can be useful for analytics, but it should not be treated as proof that a visitor belongs to a particular audience. An authenticated user may provide reliable account context, yet personal data must be handled with care and displayed only after the relevant permissions have been checked.
Before implementing the page, write down the selection rule in plain language. For example: select an active campaign by its public slug, use its approved headline and image, and show a default page when no matching campaign is available. This rule will guide the model, view, tests and template.
Model the variable content as data
When several landing pages share a structure, the variable parts usually belong in a model rather than in separate templates. A campaign model might contain a public slug, headline, summary, call-to-action label, destination URL, image reference and publication status. The exact fields depend on the project, but each field should represent content or configuration that is expected to vary.
A useful model also makes publication rules explicit. A Boolean field such as is_active can be enough for a small internal tool, while a project with scheduled publishing may need start and end timestamps. The view should apply those rules consistently, so an unpublished record cannot be exposed by guessing its URL.
Keep the model focused. A landing page model should not become a storage place for arbitrary HTML entered without review. Prefer structured fields such as a headline, an optional subheading, a list of benefits and a button label. Structured content is easier to validate, translate, test and render safely.
For repeated content, a related model can be more appropriate. A campaign may have several benefit records, each with a title and description. The view can retrieve them in a defined order, and the template can loop over them. This avoids adding many similarly named columns such as benefit_one and benefit_two, which makes future changes harder.
Create a view that selects and validates the page
A class-based or function-based view can serve the same purpose. The important point is that selection and validation happen before rendering. A function-based example can be expressed as follows:
views.py
from django.shortcuts import get_object_or_404, render
def campaign_landing(request, slug):
campaign = get_object_or_404(Campaign, slug=slug, is_active=True)
context = {
'campaign': campaign,
'benefits': campaign.benefits.all(),
}
return render(request, 'landing/campaign.html', context)
This view uses the URL slug to find an active campaign. If there is no matching record, the request receives a not-found response rather than a page filled with uncertain or incomplete data. That distinction matters for search indexing, monitoring and user expectations.
The view can also prepare a more deliberate context. For example, it may choose a translated heading, calculate whether an optional section has content or select a safe destination for the primary button. Keeping these decisions in Python prevents the template from becoming a collection of nested conditions.
When the page needs several related objects, consider query efficiency. Use select_related for a single-valued relationship and prefetch_related for collections when the data access pattern requires it. The correct choice depends on the models and query. The aim is to avoid a new database query for every item rendered in a loop. Django's query inspection tools and application tests can help verify the result.
Map a clean URL to the shared view
The URL configuration should expose a stable, readable route. A path using a slug makes the relationship between the address and the selected content clear.
urls.py
from django.urls import path
from .views import campaign_landing
urlpatterns = [
path('campaigns/<slug:slug>/', campaign_landing, name='campaign_landing'),
]
The slug converter restricts the expected format before the view receives the value. It does not replace database validation, but it reduces accidental input and makes URLs more predictable. If campaign identifiers must remain stable after an editorial rename, store a dedicated slug and avoid deriving it on every request.
For language-specific pages, a language prefix or Django's internationalisation tools may be appropriate. For product pages, a product identifier may be more suitable than a campaign slug. The same template can serve all of these cases if the context has a consistent shape. A useful convention is to pass a primary object named according to its role, such as campaign or product, rather than passing many unrelated values with ambiguous names.
Build the template around shared structure
The template should describe the page structure and use context variables where content changes. A compact example looks like this:
landing/campaign.html
{% extends 'base.html' %}
{% block content %}
<main>
<section>
<h1></h1>
<p></p>
<a href=""></a>
</section>
{% if benefits %}
<section>
{% for benefit in benefits %}
<article>
<h2></h2>
<p></p>
</article>
{% endfor %}
</section>
{% endif %}
</main>
{% endblock %}
Django's template autoescaping protects variable output in normal HTML contexts by escaping characters that could be interpreted as markup. Keep that protection enabled. Avoid marking user-controlled content as safe unless it has passed a controlled sanitisation process and the decision is justified. A value that looks like harmless text in a form may become dangerous when inserted into an attribute, a script, a style block or a URL.
The template should also handle missing optional content without leaving empty headings or awkward gaps. Conditional blocks are appropriate for a small number of presentation decisions. If the conditions begin to represent audience rules, permissions or complex selection logic, move that work into the view or a dedicated service.
Use template inheritance and reusable components
A single landing template does not mean every element must be written in one large file. Template inheritance can provide a common document shell, while includes can isolate recurring visual units.
A base template may define the document title block, navigation, main content block and footer. The landing page then overrides only the blocks it needs. A reusable button or feature card can be moved into an include, with a clearly documented context contract. For example, an include may expect label, href and an optional style value.
This structure improves maintenance in several ways:
- A change to the global navigation is made in one base template.
- A button's accessibility attributes can be reviewed in one component.
- The landing page remains focused on its content hierarchy.
- Design variations can be represented by controlled values rather than copied markup.
Use components for repeated structure, not as a way to hide complex business rules. A template tag may be appropriate when a presentation operation is genuinely reusable, but it should not replace a service that selects confidential or permission-dependent data. The closer a decision is to authentication, pricing, eligibility or authorisation, the more important it is to keep that decision outside the template.
Support variants without creating template sprawl
Personalisation often includes several visual or editorial variants. One approach is to pass a controlled variant value and use a small conditional block:
{% if campaign.layout_variant == 'compact' %}
{% include 'landing/_compact_hero.html' %}
{% else %}
{% include 'landing/_standard_hero.html' %}
{% endif %}
This is safer than accepting a template filename from a query parameter. A visitor-controlled filename can create security and maintenance problems, particularly if it influences which templates are loaded. Keep the list of variants inside application code or model validation.
For many variants, a mapping in Python is easier to audit than a long chain of template conditions. The view can associate an approved variant with a known template fragment, while the main page continues to provide shared structure. Another option is a component whose styles are controlled by a fixed class name selected from an allowlist.
Personalised content should not produce misleading combinations. Define which fields are required for each variant and validate them before publication. A campaign marked as a compact layout may need a shorter headline, while a layout with a large image may require an image with suitable dimensions and alternative text. Editorial validation is part of technical quality because the template cannot correct missing or contradictory content at render time.
Handle SEO, accessibility and performance deliberately
A personalised page still needs a stable technical foundation. Each public variation should have an appropriate document title, heading hierarchy and description. The view can pass a page title and meta description to the base template, while the landing template supplies the visible heading. Avoid generating large numbers of near-identical indexable URLs from arbitrary query parameters. Tracking parameters should be assessed as part of the site's canonicalisation and indexing strategy.
Accessibility requires more than changing text. Images need meaningful alternative text when they convey information, and decorative images should be treated accordingly. Buttons and links should describe their destination or action. A changed colour theme must preserve readable contrast, and a personalised section should remain understandable when optional content is absent. Test keyboard navigation and use semantic headings rather than styling generic elements to look like headings.
Performance depends on the complete response, not only the template. Optimise image delivery, avoid unnecessary database queries and keep third-party scripts under review. If a campaign includes an image field, validate its type and dimensions during upload or publication. Lazy loading may help below-the-fold media, but the main visual content should not be delayed without considering the effect on the first view.
Cache decisions require care. A public campaign page can often be cached by URL, while a page containing account-specific information must not be served from a shared cache. Never allow a cached personalised response to appear for another visitor. Review cache headers, session usage and reverse-proxy behaviour together.
Protect inputs, destinations and personal data
Personalisation does not remove Django's normal security responsibilities. Treat path values, query parameters, cookies and submitted form fields as untrusted input. Use model lookups, validation and allowlists rather than interpolating values into raw SQL, HTML or template filenames.
Destination URLs deserve particular attention. If an editor can enter a complete external URL, define whether that is permitted and validate the accepted schemes. If the destination should remain within the application, store a named route or an internal path instead. A page that reflects an unvalidated destination can become part of a phishing flow or an open redirect pattern.
Do not expose private attributes merely because a visitor knows a campaign identifier. Check object-level permissions whenever the selected object is not public. For authenticated personalisation, confirm that the requested record belongs to the current user or that the user has the required permission. Avoid placing sensitive information in URLs, because URLs can appear in browser history, server logs, analytics systems and referral data.
Keep Django's built-in protections enabled, including template autoescaping and CSRF protection for state-changing forms. Configure secure cookies and transport security according to the deployment environment. The security guidance published in Django's official documentation and the application security risks identified by OWASP are useful references when reviewing the design. A security review should cover both the shared template and every source that supplies its context.
Test the shared template and its data variations
A single template reduces duplication, but it increases the importance of testing the context contract. Tests should cover the selection rule, rendering and failure cases rather than checking only that the view returns a successful response.
A practical test plan includes:
- Request an active campaign and confirm that its headline, summary and call to action appear.
- Request an inactive or unknown slug and confirm that the expected not-found response is returned.
- Render the page without optional benefits and verify that no empty section heading is produced.
- Test every approved layout variant and confirm that an unapproved value does not select an arbitrary template.
- Check that HTML entered as ordinary text is escaped according to the intended context.
- Verify that a destination URL follows the application's validation rule.
- Test authenticated and unauthenticated requests separately when personal data is involved.
- Inspect database queries when a page renders a collection of related objects.
Template tests can use Django's test client and response content assertions. More detailed browser tests are useful for keyboard navigation, responsive layout and client-side interactions, particularly when the visible result depends on JavaScript. Test content boundaries too: long headings, missing images, unusual punctuation and translated strings often reveal layout assumptions that are not visible with sample text.
A practical implementation sequence
A controlled sequence keeps the work focused and makes review easier.
- Describe the page variations and identify which values are data, which are fixed structure and which are calculated decisions.
- Choose the personalisation input, such as a validated slug, and document what happens when it is absent or invalid.
- Design the model with publication status, structured fields and any required validation rules.
- Create the URL pattern and view, then write tests for successful selection and not-found behaviour.
- Build the shared base and landing templates with semantic structure and autoescaped variables.
- Extract repeated elements into includes only after the main layout is clear.
- Add controlled variants through an allowlist or explicit mapping, not through visitor-selected template paths.
- Review accessibility, SEO fields, image handling, cache behaviour and privacy implications.
- Test representative content, edge cases and permissions before publishing a campaign.
This sequence keeps personalisation grounded in a clear data model. It also prevents a common mistake: starting with conditional markup before deciding which values are trustworthy, which records are public and who is allowed to change them.
FAQ: Personalised Django landing pages
Can one template serve different campaigns?
Yes. A view can select an approved campaign record from a path parameter and pass it to a shared template. The template renders the common structure while using the record for changing content.
Should personalisation be implemented in JavaScript?
Not by default. Server-side rendering is often a better fit when the variation affects the main page content, SEO or access control. JavaScript can enhance an already rendered page, but it should not be responsible for enforcing permissions or exposing private data.
Is a query parameter suitable for selecting a private variation?
A query parameter is not proof of identity or permission. For private content, use authenticated context and object-level authorisation. For public variations, validate the parameter and consider its effect on caching and indexing.
How can unsafe editor content be avoided?
Prefer structured fields and leave template autoescaping enabled. If rich text is required, process it through a reviewed sanitisation policy before marking it safe. Do not treat an arbitrary HTML field as trusted because it came from an internal form.
When should the logic move out of the template?
Move selection, permissions, complex eligibility rules, database access and security decisions into the view or a dedicated service. Keep the template responsible for presenting a prepared, validated context.