Reputation: 53
So I'm developing a django app. I have a template which takes text as a variable. I make only part of that text a clickable link. For example I have a text "Today is John Smith's birthday" and I need "John Smith" to be an href while the other text is not. Can you help me with that please.
Upvotes: 1
Views: 4304
Reputation: 53
I guess I can call js function from template with given string as a parameter, don't know why it didn't come to my head earlier.
Upvotes: 0
Reputation: 11
you can use medium text editor
put these lines of codes in top of your page
<script src="//cdn.jsdelivr.net/medium-editor/latest/js/medium-editor.min.js"></script>
<link rel="stylesheet" href="//cdn.jsdelivr.net/medium-editor/latest/css/medium-editor.min.css" type="text/css" media="screen" charset="utf-8">
and this one down of your page
<script>var editor = new MediumEditor('.editable');</script>
and then inject the 'editable' class to your form fields that you want to manipulate(in your template's form) in your forms.py file, like this:
class form_name(forms.ModelForm):
class Meta:
model = model_name
fields = ('field_name',...)
widgets = {
'field_name': forms.Textarea(attrs={'class': 'editable medium-editor-textarea'}),
}
with this you can not only make some of your text link, but you can make more customization to your input text, like making h2, h3 or making your text bold ,italic ,link etc
but remember when you are displaying your data that you've manipulated with medium text editor you need to add |safe filter to your key in your template like this
{{ key_name|safe }}
check out this link for more information https://yabwe.github.io/medium-editor/
Upvotes: 0
Reputation: 8192
I'm assuming that the clickable name is variable, and the rest is constant text. So you would need to render a template with a context containing the name:
name = something # John Smith
url = ... # based on name
context = { "name": name, "url": url }
return render( request, 'app/birthday.html', context )
Where 'app/birthday.html'
may contain
<p>
Today is <a href="{{url}}">{{name}}</a>'s birthday
</p>
If the url you are generating is actually to an operation on your own site, you may commonly generate the url by reference to its url name (in urls.py). For example,
... href="{% url 'myapp:birthday' name %}" ...
or more commonly, where what was passed was a person object as "person":person
... href="{% url 'myapp:birthday2' person.id %}">
{{person.firstname}} {{person.lastname}} </a>'s birthday
Upvotes: 3
Reputation: 567
As I understand, you are asking something like this.
<h1>Today is <a>John Smith</a>'s birthday</h1>
Upvotes: 0
Reputation: 849
You can try write Django Template Tag: https://docs.djangoproject.com/en/3.0/howto/custom-template-tags/
Or on level View make modification with regex string and then in template use |safe
Upvotes: 0