lektor-website/content/docs/api/environment/add-build-program/contents.lr

64 lines
1.6 KiB
Plaintext
Raw Normal View History

2015-12-19 14:52:17 +01:00
title: add_build_program
---
type: method
---
signature: cls, program
---
summary: Registers a build program for a source object.
---
body:
This is very experimental API and used to register build programs for
custom source objects. This can be used to implement virtual items. This
works in combination with [generator :ref](../generator/) and
[urlresolver :ref](../urlresolver/) and is responsible for generating
artifacts out of source objects.
## Example
```python
from lektor.sourceobj import VirtualSourceObject
from lektor.build_programs import BuildProgram
2016-01-09 10:24:39 +01:00
from lektor.utils import build_url
2015-12-19 14:52:17 +01:00
class Source(VirtualSourceObject):
2016-01-09 10:24:39 +01:00
@property
def path(self):
return self.record.path + '@source'
2015-12-19 14:52:17 +01:00
@property
def source_content(self):
2016-01-09 10:24:39 +01:00
with open(self.record.source_filename) as f:
2015-12-19 14:52:17 +01:00
return f.read().decode('utf-8')
@property
def url_path(self):
2016-01-09 10:24:39 +01:00
return build_url([self.record.url_path, 'source.txt'])
2015-12-19 14:52:17 +01:00
class SourceBuildProgram(BuildProgram):
def produce_artifacts(self):
self.declare_artifact(
self.source.url_path,
sources=list(self.source.iter_source_filenames()))
def build_artifact(self, artifact):
artifact.render_template_into('view_source.html',
this=self.source)
env.add_build_program(Source, SourceBuildProgram)
2016-01-09 10:24:39 +01:00
@env.virtualpathresolver('source')
def resolve_virtual_path(record, pieces):
if not pieces:
return Source(record)
2015-12-19 14:52:17 +01:00
```
And here the example `view_source.html` template:
```html+jinja
<h2>Source for {{ this.parent.path }}</h2>
<pre>{{ this.source_content }}</pre>
```