Template tags
Common
- megforms.templatetags.megforms_extras.is_list(val) → bool
Tells whether given value is an instance of
listor its subclass
- megforms.templatetags.megforms_extras.compliance_percentage(compliance: float | None) → str
Renders compliance percentage or -
- Parameters:
compliance – compliance value as a
floatorNone- Returns:
formatted compliance value
- megforms.templatetags.megforms_extras.percentage(ratio: float | None) → str | None
Converts ratio as a percentage. If ratio is null, returns null
- Parameters:
ratio – the ratio float between 0 and 1 (inclusive)
- Returns:
formatted percentage string with 1 decimal point between 0.0% and 100.0%, or None if ratio is None.
- megforms.templatetags.megforms_extras.compliance_image_svg(compliance: Compliance, form_config: AuditFormConfig) → str
Based on compliance and form’s config returns adequate MEG Happy/Unhappy image for the compliance range in svg format
- megforms.templatetags.megforms_extras.compliance_image_png(compliance: Compliance, form_config: AuditFormConfig) → str
Based on compliance and form’s config returns adequate MEG Happy/Unhappy image for the compliance range in PNG format
- megforms.templatetags.megforms_extras.as_base64(image_field: ImageFieldFile) → str
Renders image from the image field as a base64 string so it can be inlined in a PDF document.
For example:
<img src="{{ institution.logo|as_base64 }}">
- megforms.templatetags.megforms_extras.startswith(text: str, starts: str) → bool
tells whether given string starts with another string.
- megforms.templatetags.megforms_extras.is_widget_type(value: Widget, type_name: str) → bool
Checks whether provided form widget is of specified type (by name). Checks type by name, does not check if it’s a subclass of.
- Parameters:
value – form widget instance
type_name – name of a widget class (just the class, not the full path)
- Returns:
True if widget’s type has the specified name
- Example:
{% if field.field.widget|is_widget_type:"RadioSelect" %}
- megforms.templatetags.megforms_extras.is_in_widget_types(value: Widget, comma_separated_types: str) → bool
Checks if given widget is of any of the specified types (by class name). Similar to
is_widget_type(), but operates with more than one type- Parameters:
value – form widget instance
comma_separated_types – list of comma separated widget class names (e.g. “HeadingWidget,AccordionHeadingWidget”)
- Returns:
True if widget’s type has a name from the list
- Example:
{% if field.field.widget|is_in_widget_types:"HeadingWidget,AccordionHeadingWidget" %}
- megforms.templatetags.megforms_extras.skip_hidden_fields(fields: Iterable[BoundField]) → Iterator[BoundField]
Iterates over provided fields and yields only those that are not hidden
- Parameters:
fields – (bound) form fields
- megforms.templatetags.megforms_extras.format_answer(value: Answer, field: BoundField) → str
Gets human-readable value for answer
- Parameters:
value – field’s answer
field – (bound) form field instance
- Returns:
string representing human-friendly value of the answer, such as display name in the case of a choice field.
- megforms.templatetags.megforms_extras.custom_field_value_display(value: Answer, field: CustomField) → str
Gets human-readable value for answer. An equivalent of
format_answer()for custom fields.- Parameters:
value – field’s answer
field – field instance
- Returns:
string representing human-friendly value of the answer, such as display name in the case of a choice field.
- megforms.templatetags.megforms_extras.observation_value_display(observation: CustomObservation, field: CustomField) → str
Gets human-readable value for a pair of observation and field. An equivalent of
format_answer()for custom fields.- Parameters:
observation – Observation instance
field – CustomField instance
- Returns:
- megforms.templatetags.megforms_extras.custom_file_field_value_display(value: Answer) → str
Gets human-readable value for file fields or thumbnails if applicable. An equivalent of
format_answer()for custom fields.- Parameters:
value – field’s answer
- Returns:
string representing human-friendly value of the answer, such as display name in the case of a choice field.
- megforms.templatetags.megforms_extras.level_check(audit_form: AuditForm, auditor: Auditor) → bool
Wrapper to call the utility level_edit_access function.
- megforms.templatetags.megforms_extras.institution_label(institution: Institution, capitalize: bool = False, plural: bool = False, plural_all: bool = False) → str
Label used for “institution” per institution group’s settings
- megforms.templatetags.megforms_extras.department_label(institution: Institution, capitalize=False, plural=False) → str
label used for “department” per institution’s settings
- megforms.templatetags.megforms_extras.ward_label(institution: Institution, capitalize=False, plural=False) → str
label used for “ward” per institution’s settings
- megforms.templatetags.megforms_extras.issue_label(audit_form: AuditForm, capitalize=False, plural=False) → str
- megforms.templatetags.megforms_extras.sub_issue_label(audit_form: AuditForm, capitalize=False, plural=False) → str
- megforms.templatetags.megforms_extras.counter(context: dict, name: str, init_value: int | None = None) → str
Create a counter tag in a Django template.
The counter is initialized with an integer value. To retrieve its current value, the counter without arguments is called.
Usage:
To declare and initialize a `counter` with a value of 25: {% counter 'my_counter' 25 %} To get current counter's value: {% counter 'my_counter' %}
See also
increment_counter()increments the counter value.- Parameters:
context – Django template context
name – counter name
init_value –
- Returns:
counter’s value or ‘’ if the counter’s being initialized
- megforms.templatetags.megforms_extras.increment_counter(context: dict, name: str) → str
Increment a counter (declared with the counter tag) in a Django template.
Usage:
{% increment_counter 'my_counter' %}
See also
counter()initiates counter value- Parameters:
context – Django template context
name – counter name
- Returns:
empty string
- megforms.templatetags.megforms_extras.get_item(dictionary: dict | Form, key: str) → Any | None
Gets a dictionary item using a variable key, ignoring
KeyError.- Parameters:
dictionary – a dictionary-like object such as
dictor aFormkey – key to query the dictionary
- Returns:
value under the dictionary key or null if key does not exist in the dict. e.g. if given dict is a form, returned value is a form field
- megforms.templatetags.megforms_extras.render_due_date(date: date | datetime | str | None) → str
Renders date and applies colour orange (if it’s due today) or red (if overdue). Defaults to normal text styling if date is in the future.
Warning
The tag will only work with
datetime.date/datetime.datetimetypes. Passing astris treated the same asNoneto support the way django template language passes empty value.- Parameters:
date – input date
- Returns:
<span>tag wrapping the formatted date with applied colour coding (red, orange or default - black). Returns “-” if input date is null, or an empty string.
- megforms.templatetags.megforms_extras.parse_date(value: str) → datetime
Parses datetime string into a datetime.datetime object
- megforms.templatetags.megforms_extras.get_value_from_observation(field: CustomField, observation: CustomObservation) → str
Extracts answer to given custom field from an observation. Digs into sub-observations if field is a subform field
- megforms.templatetags.megforms_extras.get_value_from_issue_by_field_name(field_name: str, issue: Issue) → str
Given a QIP issue and field name, extracts value of the field. The field can be a
CustomIssueField, or Issue model field.
- megforms.templatetags.megforms_extras.is_image_file(file: str | File) → bool
Checks whether given file is an image based on its extensions. The check is case-insensitive and includes few well known image formats recognized by most browsers.
- megforms.templatetags.megforms_extras.is_uploaded_file(file: str | File) → bool
Tells whether file was just uploaded (is
UploadedFileinstance).
- megforms.templatetags.megforms_extras.remove_newlines(val: Any) → str
Strips newlines from string, or object’s string representation
- megforms.templatetags.megforms_extras.report_content_type(name: str) → str
Gets report rule content label by its name
- megforms.templatetags.megforms_extras.report_action_type(actions: list) → str
Report rule actions formatted for display
- Parameters:
actions – report rule action choices or subset of
- Returns:
String containing a comma-separated list of labels representing the given actions.
- megforms.templatetags.megforms_extras.planning_audit_select_url(context: dict, url_name: str, audit_form_id: int | None = None)
Creates a url for the audit selector in planning tab. If all_targets, month and year are ignored.
- megforms.templatetags.megforms_extras.get_form_perms(context: dict, form: AuditForm) → PermWrapper | None
Provides
FormPermWrapperfor current user representing the permissions in the context of given form. This can give user extra permissions in addition to their global permissions as per Task #25847.- Parameters:
context – template context, should contain
user.form – an audit form instance
- Returns:
user permissions in the context of the selected form.
Noneis returned if context’s user is not an auditor.
- Usage:
{% get_form_perms audit_form as form_perms %} {% if form_perms.megforms.change_auditformconfig %} You have the permission to change form config {% endif %}
- megforms.templatetags.megforms_extras.show_permissions(group_name: str) → str
Renders list of permissions for given
Groupname. Renders nothing if group is not found.- Parameters:
group_name – name of a django permission group
- Returns:
html containing comma-separated list of permissions hidden behind an expandable “View” toggle.
- megforms.templatetags.megforms_extras.get_auditor_url(context: dict, url_name: str, auditor_id: int, pk: str | None = None) → str
Creates a url for any url name in megforms.urls.auditor_urls
- megforms.templatetags.megforms_extras.get_institution_local_url(context: dict, institution: Institution)
Get institution local url
- Parameters:
context –
institution –
- Returns:
- megforms.templatetags.megforms_extras.field_conditions_check(context: dict, field: BoundField, form: BaseAuditForm) → bool
Checks fields conditions and determine if it should be displayed works only if variable apply_field_condition is
Truein context
- megforms.templatetags.megforms_extras.is_logged_in_as_demo(context: dict) → bool
Checks if current request is a logged in demo account
- megforms.templatetags.megforms_extras.wrap_tag(text: str | SafeString, tag: str) → SafeString
Wraps given input text in an opening/closing html tag.
Use this filter to add formatting to a variable before adding it to a translatable string. Can be used multiple times to wrap text in multiple tags.
{% blocktrans with username=user.name|wrap_tag:"i"|wrap_tag:"strong" %} Hello {{username}} {% endblocktrans %} <!-- Will render as: --> Hello <strong><i>User</i></strong>
- Parameters:
text – text to wrap. If input is not a safe string, its special characters will be ecaped.
tag – name of the tag to use (e.g. ‘strong’, ‘code’), without angle brackets. This parameter is not validated, so if it’s not a valid HTML tag name, the output string may be invalid HTML.
- Returns:
safe string containing the text wrapped in given tags.
- megforms.templatetags.megforms_extras.pretty_json(value: dict) → str
Formats a JSON string so it’s easy to read.
- megforms.templatetags.megforms_extras.answer_comments(observation: ObservationOrSubObservation, field_name: str) → str
Template tag to fetch answer comments for a given observation and field name.
- Parameters:
observation – Single observation object.
field_name – Field name to filter the comments.
- Returns:
Comments as a string, only including published comments. as per task -> 29411
- Usage:
To use the answer_comments:
{% load megforms_extras %} <h3>Answer Comments: {% answer_comments observations.0 "field_name" %}</h3>
- megforms.templatetags.megforms_extras.join(*items: Any) → str
Concatenates arguments into a single string. Each item is cast to string, and resulting strings are joined together to create the output.
example usage how to create a string and store result in a variableunique_id{% join 'modal-' auditor.user.username '-' form.pk as unique_id %}
- Parm items:
any collection of objects
- Returns:
a string representing each item in the order they were passed in
- megforms.templatetags.megforms_extras.calculate_stage_position(stage_number: int, total_stages: int) → str
Calculates the percentage position for a stage in a progress bar.
The position is calculated by dividing the progress bar width by either the total number of stages then multiplying by the current stage number.
Example usage to calculate position in a progress bar:
Example usage{% calculate_stage_position forloop.counter total_stages as position %}
- Parameters:
stage_number – Current stage number
total_stages – Total number of stages
- Returns:
A string representing the percentage position (e.g., “40%”)
- megforms.templatetags.megforms_extras.notification_type_display(notification_type: str) → str
Provides an efficient template tag for accessing and displaying the notification type to the user
- Parameters:
notification_type – the type of notification as defined by the grouper in the template
- megforms.templatetags.megforms_extras.file_icon(filename: str) → str
Return appropriate icon name for in memeory files based on file extension.
- Parameters:
filename – the name of the file
Utilities
- megforms.templatetags.domain_url.domain_url(context) → str
Gets domain name for this site. Uses
megforms.utils.get_domain_url()internally and passes the current request.- Returns:
domain name pre-fixed with https (or http if localhost)
- megforms.templatetags.domain_url.absolute_url(url: str) → str
Creates absolute url for given relative url. Does not validate whether the url is already absolute.
- megforms.templatetags.arithmetic.format_percent(value: float | None) → str
Formats given value as percentage. Typically used for compliance, so it is assumed that input value will be within 0 - 1 range, or null to mark compliance as “unknown”
Note
this tag is deprecated, please use
compliance_percentage().- Parameters:
value – input value, in
0.0 <= value <= 1.0range- Returns:
Percentage value with 1 decimal point precision (e.g. 97.5%), or “-” if input value is null.
- megforms.templatetags.arithmetic.modulo(value: int | float, mod: int) → int
Performs a modulo operation on given inputs
- Parameters:
value – the input value, the dividend. It can be a
float, but it will be converted tointbefore the operationmod – the divisor
- Returns:
Reminder of the division
Files
- files.templatetags.files.file_url(file: FieldFile) → str
Given file, returns url to download the file
- files.templatetags.files.thumbnail_url(file: ImageFieldFile) → str
Given image file, returns url to its thumbnail
- files.templatetags.files.file_img(file: ImageFieldFile) → str
Renders thumbnail img tag that links to the file itself. If file does not exist, does not render the tag.
- files.templatetags.files.render_field_image(image_file: ImageFieldFile) → str
Renders img tag for given image file object
- files.templatetags.files.filename(file_path: str) → str
Renders filename, stripping off directory structure from the path
Components
- megforms.templatetags.components.empty_table_message(message: str = 'Could not find any items', *, colspan: int = 100) → str
Renders a message within a table saying there are no items. Includes the necessary tr and td tags so it can be rendered directly in table body.
Note that the default colspan of
100should work in most cases, but may not work in some browsers, so it’s advisable to pass a valid number of columns in the table if known.- Parameters:
message – The message to show
colspan – Number of columns the message should span
Example:
1{% load components %} 2{% load i18n %} 3<table class="table table-striped"> 4<thead> ... </thead> 5<tbody> 6 {% empty_table_message _("Could not find any documents") colspan=columns|len %} 7</tbody> 8</table>
- megforms.templatetags.components.sortable_th(context: RequestContext, field: str, text: str, help_text: str = None)
Renders a sortable table header element. The view that implements the sorting logic should make use of
SortableMixin- Parameters:
context – The request context.
field – The field used to sort the data via a GET request.
text – The text displayed in the table header.
help_text – added a tooltip text for span item.
- megforms.templatetags.components.progress_spinner(label: str) → str
Renders a circular spinner with a label
- megforms.templatetags.components.django_admin_link(context: dict, obj: BaseModel, classes: str = 'btn btn-default pull-right', label='Advanced editor') → str
Renders conditional Advanced Editor button. Does not render if user does not have Django Admin access, or object is not saved (pk is None)
- megforms.templatetags.components.audit_log_link(context: dict, obj: BaseModel, classes: str = 'btn btn-default pull-right') → str
Renders link to action log for given object. The action log shows actions performed on a model.
- megforms.templatetags.components.icon(icon_type: str, extra_class: str | None = None, raw_class: bool = False) → SafeString
Template tag for rendering a html icon.
- Parameters:
icon_type – The icon type to render.
extra_class – Any extra css classes to include.
raw_class – whether the function will try to add base glyphicon prefix, or treat icon_type as the full class name
{% icon 'edit' %} <!-- Will render as: --> <span class="glyphicon glyphicon-edit"></span>
:raises
AssertionError: if the icon type isn’t defined as a constant in the project.- Returns:
Html safe string.
- megforms.templatetags.components.icon_css_class(icon_type: str) → str
Template tag for getting the css class of an icon.
<span class="{% icon_css_class 'edit' %}" data-id="123"></span> <!-- Will render as: --> <span class="glyphicon glyphicon-edit" data-id="123"></span>
:raises
AssertionError: if the icon type isn’t defined as a constant in the project.- Returns:
String.
- class megforms.templatetags.components.BootstrapModalNode(nodelist, title: str | Variable = '', subtitle: str | Variable = '', modal_id: str | Variable = None, show: str | Variable = '', dismissable: str | Variable = True, size: str | Variable = '', reset_form: str | Variable = True)
See
bootstrap_modal()templatetag- Parameters:
nodelist – The nodelist.
title – The modal title.
subtitle – Text included in the modal header underneath the title.
modal_id – The id of the div.modal element.
show – whether to automatically show the modal, else modal needs to be triggered manually with jQuery
dismissable – Whether the modal can be dismissed by clicking outsude of it, or pressing ESC
size – Size of the modal as per bootstrap name labelling: “lg” or “sm”. Blank to use default modal size (medium)
reset_form – Whether the form in the modal will be reset whenever the modal is dismissed.
- render(context)
Return the node rendered as a string.
- megforms.templatetags.components.bootstrap_modal(parser: Parser, token: Token)
Render a bootstrap modal.
Common options:
- title: str
dialog title (required) for the header
- subtitle: str
smaller title for the header (optional)
- modal_id: str
ID of the modal object (optional). If not provided, a unique id will be assigned. You need to set the id if you are opening the dialog manually
- show: bool
whether the dialog should be shown automatically after the page has loaded
- dismissable: bool
Whether it should be possible to dismiss the dialog by pressing ESC, or clicking outside of it. Non-dismissable dialogs do not have x button in the corner, and will not dismiss unless done so programmatically by one of the buttons within the dialog.
Use this option if you need to force user to select an option in the dialog, or want to prevent user from accidentally closing dialog and losing unsaved data.
- size: str
Large (lg) or small (sm). Leave blank for default size. https://getbootstrap.com/docs/3.3/javascript/#modals-sizes
- reset_form: bool
Whether the form in the modal will be reset whenever the modal is dismissed.
See also
BootstrapModalNodefor more config options available as keyword arguments.Bootstrap modals official documentation.
Showing/dismissing the modal
There are multiple ways to show the modal:
Pass
show=Trueto the Templatetag to show automaticallyInvoke at any time using jQuery
$('#modal-id').modal('show');Add
data-toggle="modal" data-target="#modal-id"to a button or<a>to open when clicked
To close modal:
Add one of the buttons:
modal_button(),modal_button_cancel(),modal_button_ok()Add a button with
data-dismiss="modal"inside the modalif
dismissable=Trueis set, user cna dismiss by clicking x, or clicking outside of the modal
Examples:
Create a simple modal{% bootstrap_modal title=_('My Modal') show=True %} {% block body %}<p>This renders inside the .modal-body element</p>{% endblock %} {% block footer %}{% modal_button_ok %}{% endblock %} {% end_bootstrap_modal %}
To create a modal with a form, override the content block:{% bootstrap_modal title=title modal_id="my-modal" %} {% block content %} <form method="post"> <div class="modal-body"> {% csrf_token %} {% bootstrap_form form %} </div> <div class="modal-footer"> <button type="submit" class="btn btn-success">{% icon 'ok' %} {% trans 'Save' %}</button> </div> </form> {% endblock %} {% end_bootstrap_modal %}
- megforms.templatetags.components.modal_button(label: str, btn_icon, *, btn_class='btn-primary') → str
Renders a button that dismisses a dialog
- Parameters:
label – label of the button visible to the user
btn_icon – icon name, will be passed to
icon()tag to render the icon on the buttonbtn_class – One of the bootstrap3 button classes (e.g. btn-default, btn-success, btn-primary…)
- megforms.templatetags.components.modal_button_cancel(label: str = 'Cancel', btn_icon='remove', *, btn_class='btn-primary', **kwargs) → str
Convenience tag to render a
modal_button()with Cancel label and X icon
- megforms.templatetags.components.modal_button_ok(label: str = 'OK', btn_icon='ok', *, btn_class='btn-success', **kwargs) → str
Convenience tag to render a
modal_button()with “OK”” label and tick icon
- megforms.templatetags.components.htmx_get(trigger: str = 'load', label: str = 'Loading…', swap: str = 'innerHTML', **vals) → dict
Includes part of a template by lazy-loading it with HTMX A progress spinner is displayed while the template is being loaded.
This tag works by making a HTMX request back to the same url that rendered it,
See also
HTMXViewMixinprovides ability for view to handle the request on the back-endExample usage within a template{% htmx_get component='comments' %}
Example snippet of a view handling the lazy-laded templateclass ExampleView(HTMXViewMixin, View): def handle_htmx(self, request: HttpRequest, *args, **kwargs) -> HttpResponse: if request.GET.get('component') == 'comments': return self.render_htmx_response('comments.html')
- Parameters:
trigger –
How the htmx request should be triggered. E.g:intersect: when user reveals the content by scrolling it into view, or opening the tab.intersect once: same as intersect, but will be triggered only once.load: template will be included as soon as the page is loadedOther options: hx-trigger documentationlabel – Label for the progress spinner, will be displayed beside the spinner
swap – HTMX swap strategy (innerHTML, outerHTML, beforebegin, etc). Default: innerHTML
vals – GET Arguments for htmx
- megforms.templatetags.components.alert(message: str, level: str = 'info', dismissible: bool = False) → dict
Renders a bootstrap alert in-line. https://getbootstrap.com/docs/3.3/components/#alerts
- Parameters:
message – the message to render inside the alert, should be a translated string.
level – Choose from success, info, warning, or danger.
dismissible – Whether to add x button to the alert to allow the user to close it.
- megforms.templatetags.components.customfield_admin_link(context: dict, audit_form: AuditForm, classes: str = 'btn btn-default pull-right', label='Advanced editor') → str
Renders a ‘CustomField’ admin changelist button, filtered by audit_form, Does not render if a user does not have Django Admin access.
- megforms.templatetags.components.copy_button(copy_text: str) → dict[str, str]
Renders a button that copies the given URL to the clipboard.
- Parameters:
copy_text – text to copy on press
- megforms.templatetags.components.toast_messages(context: dict) → str
Custom template tag to display Django messages as toast notifications using toastr. Drop-in replacement for bootstrap_messages from django-bootstrap3.
This templatetag is already included in base.html and will automatically display messages in templates that inherit from base.html.
For templates that do not inherit from base.html, you need to: 1. Load the templatetag: {% load components %} 2. Include the CSS: <link href=”{% static “toastr/toastr.min.css” %}” rel=”stylesheet”> 3. Include the JS: <script src=”{% static ‘toastr/toastr.min.js’ %}”></script> 4. Add the templatetag: {% toast_messages %}
- Parameters:
context – context object of the request
- class megforms.templatetags.components.CardV2Node(nodelist, notifier_text: str | Variable = '', card_id: str | Variable = None, extra_classes: str | Variable = '')
See
card_v2()templatetag- Parameters:
nodelist – The nodelist.
notifier_text – The text for the card-v2-notifier element (optional).
card_id – The id of the section.card-v2 element (optional).
extra_classes – Additional CSS classes for the card element (optional).
- render(context)
Return the node rendered as a string.
- megforms.templatetags.components.card_v2(parser: Parser, token: Token)
Render a Card V2 component (structure only).
The card provides consistent markup structure (section + optional notifier). Additional styling and layout classes can be passed via the extra_classes parameter.
Parameters:
- notifier_text: str
Text to display in the card-v2-notifier element (optional). This is the small label that appears at the top of the card.
- card_id: str
ID of the card element (optional). Useful for targeting with JavaScript or HTMX.
- extra_classes: str
Additional CSS classes to apply to the section.card-v2 element (optional).
Examples:
Card with extra classes{% card_v2 notifier_text=_('Document information') extra_classes="documents upload-create mt20" %} <p>Card content goes here</p> {% end_card_v2 %}
Simple card without notifier{% card_v2 %} <div>Card content</div> {% end_card_v2 %}
Card with ID for JavaScript/HTMX targeting{% card_v2 notifier_text=_('Properties') card_id="properties-card" extra_classes="document-properties active" %} <form>...</form> {% end_card_v2 %}
- pdf_viewer.templatetags.pdf.pdf_viewer_url(file: FieldFile | str) → str
Returns pdf viewer url for given pdf document (url)
- Parameters:
pdf_viewer_url – pdf file field obj, or url to the pdf document
- Returns:
url to pdf viewer
- pdf_viewer.templatetags.pdf.embed_pdf(url: str | FieldFile, *, width: str | int = '100%', height: str | int = '700px') → str
Embeds a document in the page using iframe.
Important
Use
pdf_viewer_url()filter on passed url to wrap the built-in pdf in a viewer UI. Not using it may result in pdf not rendering at all if the browser does not have its own PDF viewer (i.e. Google Chrome on mobile)Example usage{% embed_pdf document.pdf_file|pdf_viewer_url %}
There are multiple ways to embed a PDF object, using
<embed>,<object>, or<iframe>tag. https://www.w3docs.com/snippets/html/how-to-embed-pdf-in-html.html https://www.geeksforgeeks.org/how-to-embed-pdf-file-using-html/- Parameters:
url – URL of the pdf document to embed, or field file instance containing a pdf document file
width – Width of the container in pixels, or other css metric
height – Height of the container in pixels, or other css metric
Java Script
- megforms.templatetags.js.get_localized_datepicker(language: str) → str | None
Gets staticfile js path for given language for bootstrap datepicker library localization
- Parameters:
language – language code, e.g. “en”
- Returns:
relative path to the js file (if exists) or none if there’s no file for the specified language
- megforms.templatetags.js.bootstrap_datepicker_script(i18n_only=False, htmx_reinit=False) → str
Renders datepicker <script> tag to load the datepicker library and required locale depending on current language.
- Parameters:
i18n_only – set to True to skip including bootstrap datepicker js, and only include localization data and configuration
htmx_reinit – set to True to re-initialize datepickers on HTMX content swaps via htmx.onLoad
- Returns:
html with the relevant
<script>tags
- megforms.templatetags.js.setup_moment_script() → str
Renders a moment setup <script> tag to set current language and apply per-language overrides, Should be loaded after loading moment script
- Returns:
html with the relevant
<script>tags
- megforms.templatetags.js.institution_config_json(institution: Institution | None) → str
Provides
institution_configjs object for given institution, or default config if institution is not known- Parameters:
institution – current institution
- Returns:
<script>tag includinginstitution_configvariable holding institution config as a json object.
- megforms.templatetags.js.auditor_preferences_json(context: RequestContext, element_id: str = 'auditor-preferences-data') → str
Returns auditor preferences as json script
- Parameters:
context –
element_id – script element id
- Returns:
- megforms.templatetags.js.set_value_placeholders_data_script(context: RequestContext, id: str) → str
Renders “set_value” placeholders data script to be used alongside review-conditions.js
- Parameters:
context –
id – the html id for the data script
- megforms.templatetags.js.set_value_placeholders_dependant_data_script(id: str, wards: Iterable[Ward] | None = None) → str
Renders “set_value” dependant placeholders data script to be used alongside review-conditions.js
- Parameters:
id – the html id for the data script
wards – list of wards
- megforms.templatetags.js.hardcoded_data_script(context: RequestContext, id: str, institution: Institution | None = None, ward: Ward | None = None, wards: list[megforms.models.Ward] = None) → str
Renders hardcoded observation data script to be used alongside review-conditions.js Returns hardcoded data & maps.
- Hardcoded data:
ward, if ward provided
department, if ward provided
institution, if institution provided or if the form excepts only one institution
- Hardcoded maps:
ward_department, maps ward ID to department ID
ward_institution, maps ward ID to institution ID
- Parameters:
id – the html id for the data script
institution – institution
ward – ward
wards – list of wards
- megforms.templatetags.js.js_catalog() → str
Renders JS Catalog <script> tag. Returns a script pointing at the static translation file for the current language,
If the translation file for current language is not present, it will gracefully fall back to the less efficient JS Catalog django view.
- megforms.templatetags.google_analytics_4.google_analytics_4(context)
Google Analytics tracking template tag. Renders Javascript code to track page visits. You must supply your website property ID (as a string) in the
GOOGLE_ANALYTICS_4_PROPERTY_IDsetting.
Feedback form
- megforms.templatetags.feedback.feedback_button(context) → str
Renders feedback button and popup
- Parameters:
context – template context, must contain
request.
Docs
- megdocs.templatetags.megdocs.bookmark_button(context: dict, document: Document, btn_classes='btn btn-default', label='')
Renders simple bookmark form with button. Requires that view class implements BookmarkViewMixin
- megdocs.templatetags.megdocs.version_approval_time(version_approvals: list[megdocs.models.VersionApproval], reviewer: Auditor, step_index: int) → str
Renders the version approval time for the user and version, at the given step index
- Parameters:
version_approvals – a list of pre fetched version approvals
reviewer – the username of the reviewer to fetch the auditor object
step_index – the current index of the step which will be used to get the version approval object
- megdocs.templatetags.megdocs.step_approved_by(version_approvals: list[megdocs.models.VersionApproval], reviewer: Auditor, step_index: int) → bool
Checks if the version is approved by the reviewer at the given step index
- Parameters:
version_approvals – a list of pre fetched version approvals
reviewer – the Auditor object to check approval for
step_index – the current index of the step which will be used to get the version approval object
- megdocs.templatetags.megdocs.step_is_current(step_index: int, approval_config: VersionApprovalConfig) → bool
Returns a boolean variable to determine whether or not the step index in the template is equal to the approval config current step
- Parameters:
step_index – the step index given in the template
approval_config – the version approval config object to compare against
- megdocs.templatetags.megdocs.step_is_approved(step_index: int, approval_config: VersionApprovalConfig) → bool
Returns a boolean variable to deterine whether the current step in the template has been approved
- Parameters:
step_index – the step index given in the template
approval_config – the version approval config object to compare against
- megdocs.templatetags.megdocs.share_object_url_clipboard(context: Context, obj: Model | ModelWithAbsoluteUrl, button_text: bool = False) → dict
Renders an icon button with a js script that allows the user to copy a object’s hyperlink to their clipboard
- Parameters:
context – the context object from the view that will be used to build the request
obj – The object that will be used to build the hyperlink
button_text – Optional boolean parameter to determine whether to show text in button
- megdocs.templatetags.megdocs.step_group(version: Version, version_approvals: list[megdocs.models.VersionApproval], approved_by: bool = False, is_approval_step: bool = True)
Render a step group for approval workflow.
- Parameters:
version – Version object
version_approvals – a list of prefetched version approval objects
approved_by – Boolean value to determine if step is approved (None means pending)
is_approval_step – Boolean value to determine whether this is an approval or review step
- megdocs.templatetags.megdocs.render_document_checked_users(document: Document) → dict[str, Any]
Renders table of users who ticked checkboxes for the given document version
- megdocs.templatetags.megdocs.render_diff(content1: str, content2: str) → dict
Renders diff of the two strings
- Parameters:
content1 – original content
content2 – new content to compare against the original
- megdocs.templatetags.megdocs.static_document_icon_url(filename: str, default_icon: str | None = 'pdf.svg') → str
Return document icon resource url from filename
- Parameters:
filename –
default_icon – default icon filename in
images/document_icons/folder
- Returns:
- megdocs.templatetags.megdocs.is_reviewer(auditor: Auditor, version: Version) → bool
Check if auditor is the reviewer for the given version
- Parameters:
auditor – The Auditor object to check
version – The Version object to check against
- Returns:
True if auditor is the reviewer, False otherwise
- megdocs.templatetags.megdocs.can_edit_drafts(context: dict) → bool
Check if the current user can edit document drafts, accounting for global permissions, folder-level permissions, and author status.
- Parameters:
context – Template context dictionary containing request and institution
- megdocs.templatetags.megdocs.can_view_folder_rules(context: dict) → bool
Check if the current user can view folder permission rules, accounting for global permissions and folder-level permissions.
- Parameters:
context – Template context dictionary containing request and institution
- megdocs.templatetags.megdocs.can_edit_documents(context: dict) → bool
Check if the current user can edit documents, accounting for global permissions, folder-level permissions, and author status.
- Parameters:
context – Template context dictionary containing request and institution
QIP
- qip.templatetags.qip.can_user_edit_issue(context: dict, issue: Issue)
Whether current user can edit the given issue
- qip.templatetags.qip.is_status_disabled(context: dict, issue: Issue) → bool
Whether status field is disabled for given issue based on user permissions and audit form config
- qip.templatetags.qip.link_qip_submission_report(institution_slug: str, issue: Issue, display_text: bool | None = False) → str
Render a link or button that directs to the submission report for a given issue.
- Parameters:
institution_slug – The slug of the institution, used in the URL for the submission report.
issue – The instance of the Issue object for which the submission report link should be generated.
display_text – If True, the button will include additional text beside the icon; useful in issue_update_view.html.
- Returns:
A formatted HTML string for the submission report link, or an empty string if the issue or institution_slug is invalid.
- qip.templatetags.qip.issue_edit_btn(context, issue: Issue)
Renders edit button for QIP issue if user has the permission to edit it.
- qip.templatetags.qip.issue_edit_inline_btn(context, issue: Issue)
Renders edit button for QIP issue if user has the permission to edit it.
- qip.templatetags.qip.format_order_by(params: dict, value: str, direction: str) → str
Append order by field to the links on some QIP table headers.
- Parameters:
params – Current url parameters in the GET request
value – current value being sorted at
direction – Current direction of sorting asc/desc
- qip.templatetags.qip.qip_sortable(field: str) → bool
Checks if a specific field is sortable in QIP table
- Parameters:
field – field name to check if sortable or not
- qip.templatetags.qip.sort_direction_class(field: str, url_order_by: str = None) → str | None
Get the correct class name for the direction of sorting
- Parameters:
url_order_by – parameter in the GET url which is the order by field
field – the field name associated to each header in qip table
- qip.templatetags.qip.is_current_sort_field(field: str, order_by: str = None) → bool
Checks whether the field is the current ordering field
- Parameters:
field – name of field to check if it is being used for ordering
order_by – the current order by parameter in the URL
Messaging
- messaging.templatetags.messaging_extras.channel_type_icon(channel_type: str) → SafeString | None
Returns channel’s icon based on its type
- Parameters:
channel_type – One of the
CHANNEL_TYPE_CHOICES- Returns:
icon html string, or null of channel type is not valid
eGuides
- eguides.templatetags.eguides_extras.replace_section_urls_public(context, value) → str
Replaces the mobile section link with a web link. Changes ‘section://slug-link’ to ‘/public/eguide-slug/slug-link’
- eguides.templatetags.eguides_extras.get_institution_logo_url(context) → str
Renders relative url to institution logo, or falls back to MEG logo. Returned url is a
/media/or/static/path, depending on whether institution has a logo.The institution used in this templatetag is current user’s institution (if logged in) or institution of the eGuide being viewed (
eguidetemplate variable)
- eguides.templatetags.eguides_extras.indent_hyphen_public_eguide(value: int) → str
Renders hyphen (“-”) as many times as passed in
value.- Returns:
string containing hyphens, for example “- - - - -” for input of
5